DropdownListFor默认值

有一种简单的方法来添加一个“ – 请select – ”默认选项到一个DropDownListFor在MVC 3?

所以,我做了这样的事情:

@Html.DropDownListFor(model => model.Dessert, new SelectList(Model.AvailableDesserts, "DessertID", "DessertName"), "---Select A Dessert ---") 

似乎工作得很好。 我的viewmodel中的Dessert是用户select的。 AvailableDesserts是一个AvailableDesserts的集合。 希望有所帮助。

SelectList上有几个扩展方法

  public static SelectList PreAppend(this SelectList list, string dataTextField, string selectedValue, bool selected=false) { var items = new List<SelectListItem>(); items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue }); items.AddRange(list.Items.Cast<SelectListItem>().ToList()); return new SelectList(items, "Value", "Text"); } public static SelectList Append(this SelectList list, string dataTextField, string selectedValue, bool selected=false) { var items = list.Items.Cast<SelectListItem>().ToList(); items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue }); return new SelectList(items, "Value", "Text"); } public static SelectList Default(this SelectList list,string DataTextField,string SelectedValue) { return list.PreAppend(DataTextField, SelectedValue, true); } 

然后我的剃刀看起来像:

 @Html.DropDownListFor(m=>m.SelectedState, Model.StateList().Default("Select One","")) 

你好,试试这个(如果你使用DisplayFor方法)

 private IEnumerable<SelectListItem> AddDefaultOption(IEnumerable<SelectListItem> list, string dataTextField, string selectedValue) { var items = new List<SelectListItem>(); items.Add(new SelectListItem() { Text = dataTextField, Value = selectedValue}); items.AddRange(list); return items; } 

然后,只需将此代码添加到您的控制器

 //lambda expression binding ViewBag.YourList = db.YourTable.Select(x => x).ToList().Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DisplayName.ToString() }); ViewBag.YourList = AddDefaultOption(ViewBag.YourList, "Select One...", "null", true); 

最后在视图中,您可以显示一个下拉式combobox,就像这样

  <div class="editor-label"> Your Label </div> <div class="editor-field"> @Html.DropDownListFor(model => model.ForeignKey, (IEnumerable<SelectListItem>)ViewBag.YourList) </div> 

我想将默认值设置为被称为SiteType的Urlparameter passing的内容:

  <div class="form-group"> @Html.LabelFor(model => model.Type, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(model => model.Type, ChangeOrderSite.SiteTypeNames.Select(s => new SelectListItem { Text = s.Value, Value = s.Key.ToString(), Selected = s.Key.ToString() == Request["SiteType"] }), new { @class = "control-label col-md-2" }) @Html.ValidationMessageFor(model => model.Type) </div> </div> 

我的下拉列表是“网站types”列表。