Html.DropDownList Not Working?

by Mikael Henriksson 31. January 2009 14:17

It’s actually pretty though not very easy to grasp and I couldn’t really find any information about my little problem but here is my explanation on how to get it working! :)

All you need to do is:

<%= Html.DropDownList("CustomerID") %>

And this is why. I know it says that the DropDownList takes a SelectList as a second parameter but you actually supposed to solve this issue in the controller (And this is a very good solution since it makes the presentation layer way less cluttered (logic should NOT be in the Views)!

public ActionResult Edit(int id)
{
    var invoiceRepository = new InvoiceRepository(1);
    var invoice = invoiceRepository.GetSingle(id);

    IList<Product> products = invoiceRepository.GetProducts(id);
    IList<Workday> workdays = invoiceRepository.GetWorkdays(id);

    invoice.CompanyReference.Load();
    int companyId = invoice.Company.ID;
    ICriterion<Customer> criterion = 
		new Criterion<Customer>(c => c.Company.ID == companyId);
    var repository = new Repository();
    IList<Customer> customers = repository.GetAll(criterion);
    ViewData["Products"] = products;
    ViewData["Workdays"] = workdays;

    ViewData["CustomerID"] = new SelectList(customers, "ID", "Name");
    ViewData["Invoice"] = invoice;

    return View(invoice);
}

What I do here is to tell the the presentation layer that the CustomerID contains a SelectList of Customer and that the value field is ID and the display field is Name. Then MVC handles this for you!

Tags:

MVC

blog comments powered by Disqus

About the author

Life architect specialized in programming