Introduction
This code is used to build the generic dropdownlist to query the list from DB so that no need to reproduce the code everywhere .
Using the code
Step 1
Write a static method to perform the logic . Here I query from the database using Entity Framework and for the type
T
, you need to pass the model name (Database -table name),
since the Razor HTML helper accepts the type SelectListItem
, we must have the same return type
public class Helpers
{
public static List<SelectListItem> GetDropDownList<T>(
string text, string value, string selected) where T : class
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = string.Empty });
IQueryable<T> result = Db.Repository<T>();
var lisData = (from items in result
select items).AsEnumerable().Select(m => new SelectListItem
{
Text = (string)m.GetType().GetProperty(text).GetValue(m),
Value = (string)m.GetType().GetProperty(value).GetValue(m),
Selected = (selected != "") ? ((string)
m.GetType().GetProperty(value).GetValue(m) ==
selected ? true : false) : false,
}).ToList();
list.AddRange(lisData);
return list;
}
}
Step 2
Then in the Controller action, you can call the static method as below and pass the result to the MVC view using the ViewBag:
var countryList = Helpers.GetDropDownList<Country>("Name", "CountryCode", "SG");
var currencyList = Helpers.GetDropDownList<CurrencyCode>("Name", "Code", "AUD");
ViewBag.CountryCode = countryList;
ViewBag.Currency = currencyList;
Step 3
You can call the ViewBag in the dropdownlist Html Helper as shown below in the MVC Razor View which is tied to the model.
@model MvcApplication1.Model.Model1
<tr>
<td>@Html.LabelFor(model => model.Currency):</td>
<td>@Html.DropDownList("Currency", ViewData["Currency"]
as SelectListItem[]) @Html.ValidationMessageFor(model => model.Currency)</td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.Country):</td>
<td>@Html.DropDownList("Country",
ViewData["Country"] as SelectListItem[])
@Html.ValidationMessageFor(model => model.CountryCode)</td>
</tr>