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

耗尽温柔 提交于 2019-11-29 17:57:58

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!