【问题标题】:Assign Value to option in dropdownlist in mvc 4 razor在 mvc 4 razor 的下拉列表中为选项分配值
【发布时间】:2014-05-21 20:34:33
【问题描述】:

我对 MVC 4 还很陌生,所以这听起来很简单。

这是一段剃须刀代码:

 @Html.DropDownListFor(model => model.ResidentTypes[i].LevelID, new SelectList(Model.LevelOfTraining, "Value", "Text", Model.ResidentTypes[i].LevelID), "--Select--", new { @style = "" })

它会显示一个下拉列表,其中包含几个选项和一个“--Select--”。 但是选择没有分配值。谁能告诉如何将值添加为 0 到 "--Select--" 选项??

【问题讨论】:

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


【解决方案1】:

您可以使 LevelID 可以为空 - int?;我在SelectList 类上使用扩展方法。

public static class SelectListExtension {
  public static SelectList Prepend(this SelectList list, string text, string value, bool selected = false) {
    if (list == null) {
      throw new ArgumentNullException("list");
    }

    return new SelectList(new SelectListItem[] { 
      new SelectListItem { 
        Selected = selected, 
        Text = text, 
        Value = value 
      }
    }.Union(list), "Value", "Text");
  }

  public static SelectList Default(this SelectList list, string text, string value = null) {
    if (list == null) {
      throw new ArgumentNullException("list");
    }

    return list.Prepend(text, value, true);
  }

  public static SelectList Default(this SelectList list) {
    if (list == null) {
      throw new ArgumentNullException("list");
    }
    // localization here
    string defaultMessage = "-- SELECT --";
    return list.Default(defaultMessage);
  }
}

【讨论】:

    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多