Loading DropdownList in ASP.NET MVC

In ASP.NET MVC you can load DropDownList easily. There are different ways for loading this. Here I am demonstrating a simple example for loading some countries.
Create a Generic class DropDownList<T> which contain a method LoadItems which return Sytem.Web.Mvc.SelectList
public static class DropDownList<T>
{
public static SelectList LoadItems(IList<T> collection, string value, string text)
{
return new SelectList(collection, value, text);
}
}

Create two class such as Country and a CountryViewModel which contain  a property for getting PostedCountryId
public class CountryViewModel
{
public int PostedCountryId { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}

Then I am going to fill the countries list in to a ViewData. You can also use ViewBag instead
public class DropDownController : Controller
{
public ActionResult Index()
{
ViewData["LoadCountries"] = DropDownList<Country>.LoadItems(CountriesCollection(), "Id", "Name");
return View();
}
public List<Country> CountriesCollection()
{
var list = new List<Country>
{
new Country{Id = 1,Name = "India"},
new Country{Id = 2,Name = "Brazil"},
new Country{Id = 1,Name = "Gautemala"},
new Country { Id = 1,Name = "Spain"}
};
return list;
}
}

From the view you can retrieve the ViewData value to DropDownListFor helper
@model MVCCollection.Controllers.CountryViewModel
@using (Html.BeginForm("Create", "DropDown", FormMethod.Post))
{
@Html.DropDownListFor(model => model.PostedCountryId, (IEnumerable<SelectListItem>) ViewData["LoadCountries"], "--Select--", new {@class = "select"})
<input type="submit" value="PostSelectedCountryId"/>
}

When you call the submit button you will get selected country id to CountryViewModel class like below
1

Enjoy coding…

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