0

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

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:

@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>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.