Reputation: 1
I am getting this error in one project and the code works perfectly fine on another project. I have tried multiple to duplicate the code as it is. Is there a way to find where the error originated from??
@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>
Upvotes: 0
Views: 158
Reputation: 24957
I suspected ViewBag.RolesForThisUser
itself already contains a string
, neither an array nor collection of strings (e.g. string[]
or List<string>
), hence using foreach
loop is pointless (and string
itself contains char[]
array which explains why type conversion failed). You can simply display it without 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>
}
Or assign a string collection to ViewBag.RolesForThisUser
from GET
method so that you can use foreach
loop, like example below:
Controller
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>
}
Upvotes: 1