Wednesday, November 16, 2011

Populate a Dropdown in MVC

Scenario- How to develop a reusable component to populate all dropdowns in MVC applications.

Design-
Repository class - LookupRepository.cs that will fetch lookup values from DB.
Static Extension class - LookupExtension.cs will have method that will extend Dictionary object and return list of SelectListItems.
Static Helper class - LookupHelper.cs will call the repository, cast the result to list of SelectListItems and build SelectList.

Model class

public class Sample
{
public int Country {get; set;}
public SelectList Countries {get; set;}
}


Controller code

public ActionResult Index()
{
var model = new Sample();
model.Countries = LookupHelper.Countries;
return View(model);
}


Index.chtml code

@model Sample
@Html.DropDownListFor(m => m.Country, Model.Counties, new { @style = "width:86%" })


LookupHelper.cs


public static SelectList Counties
{
get
{
return new SelectList(_lookupRepository.Countries.ToSelectListItems(), "Text", "Value");
}
}

LookupExtensions

public static IEnumerable ToSelectListItems(this IDictionary items, string selected = "1")
{
return items.Select(k =>
new SelectListItem
{
Selected = (k.Value == selected),
Text = k.Key,
Value = k.Value
});
}

No comments:

Post a Comment