How to set the default value for Html.DropDownListFor in MVC

后端 未结 2 1487
失恋的感觉
失恋的感觉 2020-12-22 07:29

i have following code : controller method:

 public ActionResult Register(int? registrationTypeId)
        {
            IEnumerable

        
相关标签:
2条回答
  • 2020-12-22 08:12

    The Wrong Way To Do This

    var accountTypes = new SelectList(accountTypes, "AccountTypeId", "AccountTypeName");
    
    foreach(var item in accountList)
        if (item.AccountTypeId == registrationTypeId)
            item.Selected = true;
    
    ViewBag.AccountTypes = accountTypes;
    

    In view,

    @Html.DropDownListFor(n => n.AccountType, (SelectList)ViewBag.AccountTypes)
    
    0 讨论(0)
  • 2020-12-22 08:24

    I would highly recommend that you don't pass your list through the view bag. have seen too many questions where that has caused major issues. add this to your model

    public List<SelectListItem> AccountTypes { get; set; }
    

    in your controller in the get method set your default and set your list

    Model.AccountType = 1;  // change the one to your default value
    Model.AccountTypes = accountTypes;  //instead of ViewBag.AccountTypes = accountTypes;
    

    then on your view

    @Html.DropDownListFor(x => x.AccountType, Model.AccountTypes)
    

    setting AccountType before passing the model to the view will set the default and the selected value on the view will be passed back in that same value.

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