首页 > 解决方案 > 无法将类型“字符”转换为“字符串”

问题描述

我在一个项目中遇到此错误,而代码在另一个项目中运行良好。我已经尝试过多次复制代码。有没有办法找到错误的来源?

@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>

标签: asp.net-mvcstring

解决方案


我怀疑ViewBag.RolesForThisUser它本身已经包含 a string,既不是数组也不是字符串集合(例如string[]or 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>
}

或者将字符串集合分配给ViewBag.RolesForThisUserfromGET方法,以便您可以使用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>
}

推荐阅读