Nelssen
Nelssen

Reputation: 1147

Dropdownlist selects always the first item regardless of selected property (ASP.NET MVC)

I want to use a dropdownlist, the problem is that the selected item is always the first item added. And the selected property set in the controller is completly ignored.

Maybe I'm missing something basic but I'm not seeing nothing wrong in the code.

Ho wever I can see that the generated HTML Code does not display the selected property either.

Do you guys find anything wrong in the code below?

Controller

public ActionResult Index()
        {

            HomeModel model = new HomeModel();
            List<SelectListItem> ddlItems = new List<SelectListItem>();
            SelectListItem Opt1 = new SelectListItem { Text = "Opt1", Value = "1" };
            SelectListItem Opt2 = new SelectListItem { Text = "Opt2", Value = "2", Selected = true };
            ddlItems.Add(Opt1);//The first item added is always the selected one
            ddlItems.Add(Opt2);
            model.DDL = ddlItems;
            return View("Index", model);
        }

Model

  public class HomeModel
    {
        public List<SelectListItem> DDL { get; set; }

    }

View

@Html.DropDownListFor(m => m.DDL, Model.DDL, new { id = "ddlId"})

Generated HTML

 <select name="DDL" id="DDL">
    <option value="1">Opt1</option>
    <option value="2">Opt2</option>
 </select>

Upvotes: 0

Views: 3525

Answers (1)

user3559349
user3559349

Reputation:

You cannot bind a <select> to a complex object (in your case List<SelectListItem>). Your model needs a property

public class HomeModel
{
    public int SelectedItem { get; set; }
    public List<SelectListItem> DDL { get; set; }
}

and your method would be

public ActionResult Index()
{
    HomeModel model = new HomeModel()
    {
       SelectedItem = 2, // set the default selection
       DDL = new List<SelectListItem>
       {
           new SelectListItem { Text = "Opt1", Value = "1" },
           new SelectListItem { Text = "Opt2", Value = "2" }
       }
    };
    return View(model); // no need for the view name
}

Note that there is no point setting the Selected property of SelectListItem when you binding to a model (it's the value of the property that determines what is selected)

Then your view will be

@Html.DropDownListFor(m => m.SelectedItem, Model.DDL)

Upvotes: 2

Related Questions