繁体   English   中英

无法将类型'char'转换为'string

[英]Cannot convert type 'char' to 'string

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

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

我怀疑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>
}

或从GET方法为ViewBag.RolesForThisUser分配一个字符串集合,以便您可以使用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>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM