【问题标题】:Razor syntax for DropDownListForDropDownListFor 的 Razor 语法
【发布时间】:2016-02-09 14:36:13
【问题描述】:

如何使用 HTML 助手编写下面的代码?

<select name="CountryId">
    @foreach (var c in ViewBag.Counties) {
        <option value="@c.Id">@c.Name</option>
    }
</select>

上面的代码将在我的浏览器中提供正确的 html 代码。但是,如果我在选项标签中使用 value 属性 下方的 HTML 帮助器,则会丢失。

@Html.DropDownListFor(
    model => model.CountryId, 
    new SelectList(ViewBag.Countries, "Name"), 
    new { htmlAttributes = new { @class = "form-control" } }
)

如果您知道ViewBag.Counties 是来自List&lt;Country&gt; 类型的对象并且具有Name(字符串类型)和CounrtyId(int 类型)属性,那么这段代码有什么问题。

【问题讨论】:

    标签: asp.net-mvc razor html.dropdownlistfor


    【解决方案1】:

    试试这个。您的选择列表项类应该在父类中创建,该父类是您在视图页面中绑定的模型类。

     @Html.DropDownListFor(model => model.CountryId,new SelectList(ViewBag.Countries,"CountryID", "CountryName"),new {@class='form-control'}) 
    

    【讨论】:

      猜你喜欢
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多