MVC5 - How to set “selectedValue” in DropDownListFor Html helper
如问题所述:
如何在DropDownListFor HTML帮助程序中设置selectedValue?
尝试了其他大多数解决方案,但都没有成功,这就是为什么我要提出一个新问题。
这些都无济于事:
1 2 3 4 5 6 7 | @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。
当您使用
在内部,这些方法生成自己的
1 | @Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita,"Id","Naziv", 2)) |
请注意,您可以检查源代码,尤其是
若要在首次渲染视图时显示选定的选项,请在将模型传递给视图之前,在GET方法中设置属性的值
我还建议您的视图模型包含属性
1 2 3 4 5 6 | var model = new YourModel() { TipoviDepozita = new SelectList(yourCollection,"Id","Naziv"), TipPopustaId = 2 // set the selected option } return View(model); |
所以视图变成
1 | @Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class ="form-control" }) |
确保您的返回Selection Value是一个String而不是String,并且在模型中声明时为int。
例:
1 2 3 4 | public class MyModel { public string TipPopustaId { get; set; } } |
1 2 3 4 5 6 7 | public static class EnumHelper { public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue) { return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n),"Key","Value", selectedValue); } } |
在您看来:
1 2 | @Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role), new { htmlAttributes = new { @class ="padding_right" } }) @Html.ValidationMessageFor(model => model.Role,"", new { @class ="text-danger" }) |
代替EnumToList使用其他列表,然后选择Listtype属性的Key和Value。