Click here to Skip to main content
15,895,812 members
Articles / Web Development / ASP.NET
Tip/Trick

MVC Generic Dropdownlist for Razor

Rate me:
Please Sign up or sign in to vote.
4.79/5 (8 votes)
14 Nov 2013CPOL 76.6K   9   10
Building a generic dropdownlist in MVC for razor view

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

C#
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:

C#
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. 

C#
@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>  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow do i get the selected item value? Pin
shashank1711-Mar-15 22:57
shashank1711-Mar-15 22:57 
GeneralThanks a lot! Pin
Eric Castellon24-Nov-14 10:02
Eric Castellon24-Nov-14 10:02 
QuestionWhat is DB here.. Pin
ani007_639-Mar-14 1:33
ani007_639-Mar-14 1:33 
AnswerRe: What is DB here.. Pin
tsoh_tan1-Sep-14 16:50
tsoh_tan1-Sep-14 16:50 
QuestionHow to use with ADO.NET Entity Data Model .edmx ? Pin
anrorathod9-Feb-14 5:52
anrorathod9-Feb-14 5:52 
QuestionQuestion about Repository Pin
Jorge Lonzo24-Nov-13 5:52
Jorge Lonzo24-Nov-13 5:52 
AnswerRe: Question about Repository Pin
Sumathi125-Nov-13 1:26
Sumathi125-Nov-13 1:26 
GeneralRe: Question about Repository Pin
saimm15-Feb-17 20:27
saimm15-Feb-17 20:27 
can u give me sample of repositry?
QuestionGood job Pin
David Steverson15-Nov-13 6:42
professionalDavid Steverson15-Nov-13 6:42 
AnswerRe: Good job Pin
Sumathi120-Nov-13 20:41
Sumathi120-Nov-13 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.