【问题标题】:Html.LabelFor statement not displaying as assigned valueHtml.LabelFor 语句未显示为指定值
【发布时间】:2012-10-05 20:06:18
【问题描述】:

我通过 Html.LabelFor 帮助器在 foreach 语句中显示 GuarantorName。

但是,我没有得到预期的结果。

它没有显示 GuarantorName 的实际值,而是像这样简单地打印: 标签值表示实际字段名称:GuarantorName,而我需要在调试期间验证的该字段名称的实际值(如“Bill Yeager”)具有各种不同的名字。

在调试期间,我可以在列表中看到我在集合中有实际的名字。

我怎样才能做到这一点?

这是我对代码的看法:

@foreach (var item in Model.Guarantors)
                {
                    <td>
                        @Html.CheckBoxFor(model => item.isChecked)
                        @Html.LabelFor(model => item.GuarantorName)
                    </td>
                }

如果我尝试这样做,我会收到以下错误:

@Html.DisplayFor(model => item.GuarantorFirstName + item.GuarantorLastName)

异常详细信息:System.InvalidOperationException:模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式。

Source Error:


Line 95:                     <td>
Line 96:                         @Html.CheckBoxFor(model => item.isChecked)
Line 97:                         @Html.DisplayFor(model => item.GuarantorFirstName + item.GuarantorLastName)
Line 98:                     </td>
Line 99:                 }

【问题讨论】:

    标签: asp.net-mvc form-helpers


    【解决方案1】:

    LabelFor 显示属性名称。您希望 DisplayFor 显示该字段的值。

    @foreach (var item in Model.Guarantors)
                    {
                        <td>
                            @Html.CheckBoxFor(model => item.isChecked)
                            @Html.DisplayFor(model => item.GuarantorName)
                        </td>
                    }
    

    【讨论】:

    • 如果我想结合名字和姓氏呢?我想摆脱名称之间的空格....我有以下代码,但它产生以下输出: Html.DisplayFor(model => item.GuarantorFirstName) " " @Html.DisplayFor(model => item.GuarantorLastName) 标记 " " Eid
    • 嗯,去掉“”也许吧?不知道你到底是什么意思。
    • 我只想在名字和姓氏之间留一个空格。
    • 啊,我明白了。也许在两者之间添加 &nbsp,你目前有“”。例如。 Html.DisplayFor(model => item.GuarantorFirstName) &nbsp @Html.DisplayFor(model => item.GuarantorLastName)
    【解决方案2】:
    @foreach (var item in Model.Guarantors)
                    {
                        <td>
                            @Html.CheckBoxFor(model => item.isChecked)
                            @Html.DisplayFor(model => item.GuarantorName)
                        </td>
                    }
    
    
    And also we can use when used IList<Model>
    
    @for(int i=0;i<model.Guarantors.count();i++)
    {
     <td>
                            @Html.CheckBoxFor(model =>model[i].isChecked)
                            @Html.DisplayFor(model => model[i].GuarantorName)
                        </td>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2011-09-09
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多