Cannot convert type 'char' to 'string
Cannot convert type 'char' to 'string
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>
1 Answer
1
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
:
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>
Or assign a string collection to ViewBag.RolesForThisUser
from GET
method so that you can use foreach
loop, like example below:
ViewBag.RolesForThisUser
GET
foreach
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>
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy