MVC5 - How to set “selectedValue” in DropDownListFor Html helper

前端 未结 3 1884
青春惊慌失措
青春惊慌失措 2020-11-22 05:18

As the question says: How to set selectedValue in DropDownListFor Html helper?

Tried most of the other solutions but none worked that\'s why I am opening a new quest

3条回答
  •  悲&欢浪女
    2020-11-22 05:35

    public static class EnumHelper
    {
        public static SelectList EnumToSelectList(this Type enumType, object selectedValue)
        {  
            return new SelectList(Enum.GetValues(enumType).Cast().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
        }
    }
    

    And in your View:

    @Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList(typeof(Role), Model.Role),  new { htmlAttributes = new { @class = "padding_right" } })
    @Html.ValidationMessageFor(model => model.Role, "", new { @class = "text-danger" })
    

    Instead of EnumToList use any Other List and select Key and Value of your Listtype Properties

提交回复
热议问题