Baqer Naqvi
Baqer Naqvi

Reputation: 6504

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

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 !

Upvotes: 0

Views: 7083

Answers (2)

Inspector Squirrel
Inspector Squirrel

Reputation: 2548

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)

Upvotes: 0

Matt Bodily
Matt Bodily

Reputation: 6423

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.

Upvotes: 1

Related Questions