반응형

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.

반응형

+ Recent posts