asp.net-mvc - 无法将类型“字符”转换为“字符串”
问题描述
我在一个项目中遇到此错误,而代码在另一个项目中运行良好。我已经尝试过多次复制代码。有没有办法找到错误的来源?
@if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@foreach (string s in ViewBag.RolesForThisUser) //this line
{
<li>@s</li>
}
</td>
</tr>
</table>
解决方案
我怀疑ViewBag.RolesForThisUser
它本身已经包含 a string
,既不是数组也不是字符串集合(例如string[]
or List<string>
),因此使用foreach
循环是没有意义的(并且string
它本身包含char[]
解释类型转换失败的原因的数组)。您可以简单地显示它而无需foreach
:
@if (!string.IsNullOrEmpty(ViewBag.RolesForThisUser))
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@ViewBag.RolesForThisUser
</td>
</tr>
</table>
</div>
}
或者将字符串集合分配给ViewBag.RolesForThisUser
fromGET
方法,以便您可以使用foreach
循环,如下例所示:
控制器
public ActionResult ActionName()
{
var list = new List<string>();
list.Add("Administrator");
// add other values here
ViewBag.RolesForThisUser = list;
return View();
}
看法
@if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@foreach (string s in ViewBag.RolesForThisUser)
{
<p>@s</p>
}
</td>
</tr>
</table>
</div>
}
推荐阅读
- html - 下拉菜单不会与 CSS 一起显示
- python - LogisticRegression 中的标签索引需要 Pyspark 澄清
- ansible - 如何处理 ansible 库存文件的 ansible_ssh_pass 变量中的特殊字符?
- python - 您对二进制时间序列的信号处理有什么建议吗?
- python - 我可以为 numpy 预计算/预生成伪随机数吗?
- database - Flutter中可以存储列表的数据库
- r - `r`中包`infotheo`的函数`entropy`
- tensorflow - 我无法理解 tensorflow 1 中的 LSTM 实现
- android - DateTime.now().toUtc().difference 和 DateTime.now().difference 在 dart 中给出相同的结果
- package - LoadError:预期要注册的包`Execute [ef016c93]`