MVC 5-如何在DropDownListFor HTML助手中设置“selectedValue”

MVC 5-如何在DropDownListFor HTML助手中设置“selectedValue”

问题是:如何在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。


千巷猫影
浏览 714回答 3
3回答

叮当猫咪

public&nbsp;static&nbsp;class&nbsp;EnumHelper{ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;static&nbsp;SelectList&nbsp;EnumToSelectList<TEnum>(this&nbsp;Type&nbsp;enumType,&nbsp;object&nbsp;selectedValue) &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=>&nbsp;n),&nbsp;"Key",&nbsp;"Value",&nbsp;selectedValue); &nbsp;&nbsp;&nbsp;&nbsp;}}在你看来:@Html.DropDownListFor(model&nbsp;=>&nbsp;model.Role,&nbsp;EnumHelper.EnumToSelectList<Role>(typeof(Role),&nbsp;Model.Role),&nbsp;&nbsp; new&nbsp;{&nbsp;htmlAttributes&nbsp;=&nbsp;new&nbsp;{&nbsp;@class&nbsp;=&nbsp;"padding_right"&nbsp;}&nbsp;})@Html.ValidationMessageFor(model&nbsp;=>&nbsp;model.Role,&nbsp;"",&nbsp;new&nbsp;{&nbsp;@class&nbsp;=&nbsp;"text-danger"&nbsp;})而不是EnumToList,使用任何其他列表并选择列表类型属性的键和值
打开App,查看更多内容
随时随地看视频慕课网APP