MVC – 设置SelectList的选定值

如何在没有selectedvalue的情况下实例化SelectList的selectedvalue属性;

SelectList selectList = new SelectList(items, "ID", "Name"); 

我需要在这个阶段之后设置选定的值

如果你有你的SelectList对象,只需遍历其中的项目,并设置你想要的项目的“Selected”属性。

 foreach (var item in selectList.Items) { if (item.Value == selectedValue) { item.Selected = true; break; } } 

或者与Linq:

 var selected = list.Where(x => x.Value == "selectedValue").First(); selected.Selected = true; 

晚会有点晚了,但这是多么简单:

 ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82"); 

这使用我的方法getcountries来填充一个名为国家的模型,显然,你会用任何你的数据源,模型等取代这个,然后设置ID作为select列表中的值。 那么只需添加最后一个参数,在这种情况下“82”来select默认的选定项目。

下面是如何在Razor中使用这个function:

 @Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" }) 

希望这能节省一些时间。

为什么在创build列表之后尝试设置值? 我猜你是在你的模型中而不是在你的视图中创build列表。 我build议在你的模型中创build底层枚举,然后使用它来构build实际的SelectList:

 <%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %> 

这样,您select的值始终与视图的呈现方式一致,而不是之前的方式。 此外,您不必在模型中放置任何不必要的UI类(即SelectList),并且可以不知道UI。

只需使用mvc4中的选定值的第三个参数

 @Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974")) 

这里select“974”指定的值

在我的结果中select的国家现在是卡塔尔在C#如下`

  foreach (CountryModel item in CountryModel.GetCountryList()) { if (item.CountryPhoneCode.Trim() != "974") { countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode }); } else { countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true }); } } 

除了@Womp的回答,值得注意的是,“Where”可以被删除,并且谓词可以被直接放在“First”调用中,如下所示:

list.First(x => x.Value == "selectedValue").Selected = true;

我需要在一个可编辑的网格中下拉一个预先选定的下拉值。 Afaik,select列表数据由控制器提供给视图,所以它在视图消耗之前创build。 一旦视图消耗了SelectList,我就把它交给使用标准DropDownList助手的自定义助手。 所以,一个相当轻的解决scheme。 猜测在写作的时候,它符合ASP.Net MVC的精神; 当不开心滚动自己的…

 公共静态stringDropDownListEx(这个HtmlHelper助手,string名称,SelectList的selectList,对象selectedValue)
 {
    返回helper.DropDownList(名称,新的SelectList(selectList.Items,selectList.DataValueField,selectList.DataTextField,selectedValue));
 }

道格回答了我的问题,但是我会解释我的问题到底是什么,道格如何帮助我解决你可能遇到的问题。

我打电话给jquery $.post并用我的部分视图取代我的div,像这样。

 function AddNewAddress (paramvalue) { $.post(url, { param: paramvalue}, function(d) { $('#myDiv').replaceWith(d); }); } 

这样做时,由于某种原因,当进入我的模型时,我select的属性值从未设置,直到我进入视图范围。

所以,我以前有

 @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"}) 

然而,即使Model.CustomerAddresses [i] .YearsAtAddressSelectList,被设置…它没有设置选定的值。

所以……

  @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" }) 

它的工作!

我决定不使用DropDownListFor因为它使用不显眼的validation时有问题,这就是为什么我参考以下,如果你在一个类的好奇类

 HtmlExtensions.cs [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { if (expression == null) { throw new ArgumentNullException("expression"); } ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); IDictionary<string, object> validationAttributes = htmlHelper .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata); if (htmlAttributes == null) htmlAttributes = validationAttributes; else htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value); return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes); } 

你可以使用下面的方法,这很简单。

 new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault()); 

这将自动select列表中的第一个项目。 您可以通过添加一个where子句来修改上述查询。

我通常使用这种方法

  public static SelectList SetSelectedValue(SelectList list, string value) { if (value != null) { var selected = list.Where(x => x.Value == value).First(); selected.Selected = true; return list; } return list; } 

我希望下拉列表在操作方法中selectid的匹配值。 诀窍是在创buildSelectListItem集合时设置Selected属性。 它不会以其他方式工作,也许我错过了一些东西,但最终,我的select是更优雅。

你可以编写任何方法返回一个布尔值来根据你的需求设置Selected值,在我的情况下,我使用了现有的Equal Method

 public ActionResult History(long id) { var app = new AppLogic(); var historyVM = new ActivityHistoryViewModel(); historyVM.ProcessHistory = app.GetActivity(id); historyVM.Process = app.GetProcess(id); var processlist = app.GetProcessList(); historyVM.ProcessList = from process in processlist select new SelectListItem { Text = process.ProcessName, Value = process.ID.ToString(), Selected = long.Equals(process.ID, id) }; var listitems = new List<SelectListItem>(); return View(historyVM); }