[英]Cannot convert type 'char' to 'string
我在一个项目中遇到此错误,并且代码在另一个项目上运行良好。 我已经尝试过多次复制原样的代码。 有没有办法找到错误的来源?
@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
本身已经包含一个string
,既不是数组也不是字符串的集合(例如string[]
或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>
}
或从GET
方法为ViewBag.RolesForThisUser
分配一个字符串集合,以便您可以使用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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.