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

前端 未结 3 1839
青春惊慌失措
青春惊慌失措 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:20

    Make Sure that your return Selection Value is a String and not and int when you declare it in your model.

    Example:

    public class MyModel
    {
        public string TipPopustaId { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-22 05:35

    When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.

    Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using

    @Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
    

    Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.

    To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view

    I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller

    var model = new YourModel()
    {
        TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
        TipPopustaId = 2 // set the selected option
    }
    return View(model);
    

    so the view becomes

    @Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class = "form-control" })
    
    0 讨论(0)
  • 2020-11-22 05:35
    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);
        }
    }
    

    And in your View:

    @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" })
    

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

    0 讨论(0)
提交回复
热议问题