Asp.net-mvc – ASP.NET MVC Drop Down List

asp.net-mvcdrop-down-menu

I'm a newbie with ASP.NET MVC and trying to bind a Drop Down List with a data from a database. I'm making a computer packet calculator application, basically the users can select components he/she wants into his/her computer packet from a drop down list and then send the order into a email. The components must come from a database.

I'm not familiar with the MVC model so I haven't quite understood in which folder should I put which part of the application. Right now I have

-Controllers:

–HomeController

-Models

–HomeRepository

–IHomeRepository

–Database.dbml (right now I only use a table called product and the information that I need from there is

product_description and product_price)

-Views

–Home

—- Index

—- … etc …

I have managed to get all products from products table into a bulleted list and show it at Index page. So, my HomeRepository makes a datacontext from Database.dbml. There is also a public IList ListAll() method (?) where the search sentence is written. IHomeRepository has only

public interface IHomeRepository
{
  IList<product> ListAll();
}

Somehow it works and for a while I was very happy. I tried to populate a Drop Down List in Index page like this:

    <% foreach (product m in (IENumerable)ViewData.Model
{
   Html.DropDownList("processor"m new[] {
   new SelectedListItem { Text = m.product_description, Value m.product_description }, "Select a processor")
   }
}

But it shows only as many Drop Down List as I get products from the search sentence and it show only one result in every list.

What should I do? Or how should I build this kind of application? Perhaps Web Forms should be easier to do this simple application but I need to try to use the methods of eXtreme Programming, including Test Driven Development and I understood that that isn't possible with Web Forms. Well, this XP is another story…

Many thanks.

Best Answer

Assuming your action looks like this:

public ActionResult Index()
{
    IEnumerable<Product> products = Repository.ListAll();
    return View(products);
}

And the corresponding view is strongly typed to IEnumerable<Product>:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<YourNamespace.Product>>" %>

you don't need to use a foreach statement to generate the dropdown box:

<%= Html.DropDownList("processor", Model.Select(p => new SelectListItem { 
    Text = p.product_description, 
    Value = p.product_id 
})) %>