Blog Post

Setting default value in MVC5 DropDownListFor

Wednesday, February 17, 2016 3:33 PM

I have spent some time on finding out why my DropDownListFor code does not work when using selected = true in my SelectListItem.

The issue was that selected value has not been respected and I have needed to set the value manually as default value on the property, which is fundamental change to the behavior I have been used to. This does not mean that the code was wrong and it works if you allow user to select option, but it does not work when you have a code and you are trying to pre-select an option for the user.

 

I have put together code to demonstrate below.

 

Shared code:

I like to have hard coded model using class on which I will demonstrate the code.

 

DemoModel.cs

public class DemoModel{     
   public IEnumerable Items { get; set; }      
  public int ItemValue { get; set; }  
}

 

MVC 4 DropDownListFor implementation

Controller code:

 public class DemoController : Controller
    {
        public ActionResult Index()
        {
            var model = new DemoModel();
            model.Items = new List()
            {
                new SelectListItem()
                {
                    Text = "one",
                    Value = "1",
                    Selected = false
                },
                new SelectListItem()
                {
                    Text = "two",
                    Value = "2",
                    Selected = true
                }
            };
            return View(model);
        }
    }

ViewCode:

@Html.DropDownListFor(x=>x.ItemValue, Model.Items)

 

MVC 5 DropDownListFor implementation

Controller code

 public class DemoController : Controller
    {
        public ActionResult Index()
        {
            var model = new DemoModel();
            model.Items = new List()
            {
                new SelectListItem()
                {
                    Text = "one",
                    Value = "1"
                },
                new SelectListItem()
                {
                    Text = "two",
                    Value = "2"
                }
            };
            model.ItemValue = 2;
            return View(model);
        }
    }

 

ViewCode:

@Html.DropDownListFor(x=>x.ItemValue, new SelectList(Model.Items,"Value","Text"))

 You can also access my gist with example:

https://gist.github.com/cpoDesign/0cc0a3c0b0fe457e3807