Я подозревал, что ViewBag.RolesForThisUser
сам по себе уже содержит string
, ни массив, ни набор строк (например, string[]
или List<string>
), поэтому использование цикла foreach
бессмысленно (а сам string
содержит * Массив 1007 *, который объясняет, почему не удалось преобразовать тип). Вы можете просто отобразить его без 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
из метода GET
, чтобы вы могли использовать цикл foreach
, как показано в примере ниже:
Контроллер
public ActionResult ActionName()
{
var list = new List<string>();
list.Add("Administrator");
// add other values here
ViewBag.RolesForThisUser = list;
return View();
}
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>
}