How To Set The Default Value For Html.DropDownListFor In MVC
i have following code : controller method: public ActionResult Register(int? registrationTypeId) { IEnumerable accountTypes = new List
Solution 1:
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.
Solution 2:
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)
Post a Comment for "How To Set The Default Value For Html.DropDownListFor In MVC"