Manatherin
Manatherin

Reputation: 4187

MVC DropDownListFor Value Cannot Be Null

i have the code:

<%: Html.DropDownListFor(
       model => model.CompanyName, 
       new SelectList(ViewData["ActiveCompanies"] as IEnumerable, 
       "Id", "Name"))
%>

the list is being populated properally with the names etc, but the selected item name is not being bound to the Model.CompanyName (it would be fine if the solution returns the id so i can have something like

<%: Html.DropDownListFor(
        model => model.CompanyID, 
        new SelectList(ViewData["ActiveCompanies"] as IEnumerable, 
        "Id", "Name"))
 %>

infact this would be better for my purposes, but it would be really helpful if i could find out why data isnt getting bound.

Upvotes: 2

Views: 11968

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The html helper always binds data based on the value property and not the text. Also don't use ViewData and casts. I would recommend you doing this:

<%: Html.DropDownListFor(model => model.CompanyID, 
    new SelectList(Model.ActiveCompanies, "Id", "Name")) %>

where the ActiveCompanies property is populated in the controller:

public ActionResult Index()
{
    var model = new SomeViewModel
    {
        // TODO: Use a repository
        ActiveCompanies = new[]
        {
            new Company { Id = 1, Name = "Company 1" },
            new Company { Id = 2, Name = "Company 2" },
            new Company { Id = 3, Name = "Company 3" },
        }
    }
    return View(model);
}

Upvotes: 5

Related Questions