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。
3 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
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); }}
@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" })
- 3 回答
- 0 关注
- 713 浏览
添加回答
举报
0/150
提交
取消