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

房东的猫 提交于 2019-11-30 09:57:00

问题


i have following code : controller method:

 public ActionResult Register(int? registrationTypeId)
        {
            IEnumerable<AccountType> accountTypes = new List<AccountType>
            {
                new AccountType
                {
                    AccountTypeId = 1,
                    AccountTypeName = "Red"
                },
                new AccountType
                {
                    AccountTypeId = 2,
                    AccountTypeName = "Blue"
                }
            };
           // I want to select account type on registrationTypeId
            ViewBag.AccountTypes = accountTypes;
            return View();
      }

View

<div class="col-md-10">
            @Html.DropDownListFor(n => n.AccountType,
         new SelectList(ViewBag.AccountTypes, "AccountTypeId", "AccountTypeName"), new { @class = "form-control" })
</div>

Model

public class RegisterViewModel
    { 
        [Required]
        [Display(Name = "Account Type")]
        public int AccountType { get; set; 
    }

As you can see registrationTypeId in controller , i want to set the type on its bases if it is not null ,otherwise set to red. I have tried a alot but nothing worked for me. Any help will be appreciated !


回答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.




回答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)


来源:https://stackoverflow.com/questions/27297294/how-to-set-the-default-value-for-html-dropdownlistfor-in-mvc

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