views:

21

answers:

1

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.

+2  A: 

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);
}
Darin Dimitrov
Ok so im using my repository to populate a ActiveCompanies field as you suggested and now have <%: Html.DropDownListFor(model => model.CompanyID, new SelectList(Model.ActiveCompanies, "Id", "Name"))%> however when i press submit i get System.NullReferenceException: Object reference not set to an instance of an object.
Manatherin
In your POST action you need to repopulate the `ActiveCompanies` property from your repository.
Darin Dimitrov
The list is being populated, however it doesn't seem to be binding the selected item to the CompanyID
Manatherin
How does your POST action look like?
Darin Dimitrov
[HttpPost] public ActionResult Create(CustomerModel Customer) { try { // TODO: Add insert logic here if (ModelState.IsValid) { customer.Add(Customer); return RedirectToAction("Index"); } return View(); } catch { return View(); } }
Manatherin
Does `CustomerModel` have a property called `CompanyID`?
Darin Dimitrov
Oh have worked it out now, the dropdown was not actually the problem, it was just when the submit changes was pressed that was the error view it was showing, thank you for your help tho
Manatherin