[英]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.