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

后端 未结 2 1488
失恋的感觉
失恋的感觉 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)
    

提交回复
热议问题