Posted by: Cirilo Meggiolaro | 04/21/2009

Tip of the day #189 – ASP.NET MVC – Dropdownlists

Let’s check how to work with dropdownlists on ASP.NET MVC web applications.

Basically the object you need to bind an object to a dropdownlist is the SelectList. The following overloads are available:

  • public SelectList(IEnumerable items);
  • public SelectList(IEnumerable items, object selectedValue);
  • public SelectList(IEnumerable items, string dataValueField, string dataTextField);
  • public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);

How to…

  • Create a new ASP.NET MVC Web application;
  • Right-click on Controller folder and select Add > Controller;
  • Rename it to CityController and click Add. The controller class is created;
  • Let’s write that is going to be our data source. This method builds a SelectList instance based on a generic list of cities;

public class City
{
    public string Name { get; set; }
    public int ID { get; set; }
}

public static SelectList GetCities(int index)
{
    List<City> cities = new List<City>();

    cities.Add(new City() { ID = 1, Name = “Sao Paulo” });
    cities.Add(new City() { ID = 2, Name = “Toronto” });
    cities.Add(new City() { ID = 3, Name = “New York” });
    cities.Add(new City() { ID = 4, Name = “Tokio” });
    cities.Add(new City() { ID = 5, Name = “Paris” });
    cities.Add(new City() { ID = 6, Name = “Lisbon” });

    SelectList selectList = new SelectList(cities, “ID”, “Name”, index);
    return selectList;
}

  • From the Index action method, let’s add the select list object to the ViewData dictionary and request the view to be rendered;

public ActionResult Index()
{
    ViewData[“cities”] = GetCities(1);
    return View();
}

  • Right-click on the method you’ve just coded and select Add View;
  • Create a form using the Html helper method BeginForm and add a dropdownlist and a submit button. Your form will be similar to the following:

<% using (Html.BeginForm()) { %>
<%= Html.DropDownList(“lstCity”, ViewData[“Cities”] as SelectList) %>
<input type=”submit” value=”Post” />
<% } %>

  • Build and run the application;
  • Navigating to the url http://localhost/City the view will be loaded with a dropdownlist and a submit button;
  • Let’s create now an action method that will handle the post when the user clicks the post button:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection forms)
{
    int selectedItem = Convert.ToInt32(forms[“lstCity”]);
    ViewData[“cities”] = GetCities(selectedItem);
    return View();
}

Selecting a city on the dropdownlist and clicking on post button will raise a request that reaches the Index action method overload on CityController class that accepts a HttpVerb equals Post. In our simple example, the integer variable stores the id of the selected value on the form.

That is the simplest way to load and get the selected value of the dropdownlist.

Advertisements

Responses

  1. nice tips Cirilo. have any idea if the data came from the database and u will retrieved it using a linq, how can we do it? Anyway nice blog.

  2. Hi Janlie, I’ve written a post that may help you. Check the Tip of the day #208 – ASP.NET MVC – Populating dropdownlists using LINQ to SQL

    Thanks for your comments and visit!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: