正如问题所说:如何在DropDownListFor Html助手中设置selectedValue?
尝试了大多数其他解决方案,但没有工作,这就是为什么我要开一个新问题.
这些都没有帮助:
@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { @class = "form-control" }) //Not working with or without cast @Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { @class = "form-control" }) @Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { @class = "form-control" }) @Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { @class = "form-control" })
如果可能的话,我想避免手动创建SelectListItems或ViewModel.
使用DropDownListFor()
(或DropDownList()
)方法绑定到模型属性时,它是设置所选选项的属性的值.
在内部,方法生成它们自己IEnumerable
的Selected
属性并根据属性的值设置属性,因此Selected
忽略在代码中设置属性.它唯一被尊重的时候是你没有绑定到模型属性,例如使用
@Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
请注意,您可以检查源代码,特别是SelectInternal()
和GetSelectListWithDefaultValue()
方法,看看它是如何工作的细节.
要在首次呈现视图时显示所选选项,请在将模型传递给视图之前在GET方法中设置属性的值
我还建议您的视图模型包含一个属性,IEnumerable
并SelectList
在控制器中生成该属性
var model = new YourModel() { TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"), TipPopustaId = 2 // set the selected option } return View(model);
所以观点变成了
@Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class = "form-control" })