MVC Populate Dropdown

The MVC pattern and the ASP.Net MVC have made web development rapid and easier. This pattern helps creating applications that separate the various aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling among these elements. This example will demonstrate how to populate a dropdown list from a database.

Populate Drop Down in ASP.Net MVC (ASPX and Razor)

Let's assume you would want to populate the Country dropdown list from the database on your web site Register page.

Sample Code

  • I'll be using the sample ASP.Net MVC web application (ships with MVC installation) for this example.

Country Table


Create the Country table mapping class as shown below:

/// <summary>

/// Country Class
/// </summary>
[System.Data.Linq.Mapping.Table(Name = "Country")]
public class CountryLookupEntity
    [System.Data.Linq.Mapping.Column(IsPrimaryKey = true, IsDbGenerated = true )]
    [Display(Name = "Id")]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Code { get; set; }


Inside your Account controller, create a new ViewBag or ViewData property:

public ActionResult Register()
ViewBag.CountryList = new SelectList(new User().GetCountryList(),"Code","Name");
ViewBag.PasswordLength = MembershipService.MinPasswordLength;
return View();

The following is the GetCountryList method that brings the data from your database table using LINQ to SQL or the Entity Framework, whichever you prefer to use.

public IEnumerable<CountryLookupEntity> GetCountryList()
       string conn = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
       dbContext = new DataContext(conn);
<CountryLookupEntity> cntTable = dbContext.GetTable<CountryLookupEntity>();
       return cntTable.ToList();

Now in your .aspx or .cshtml page place a control for the dropdown list with the same viewdata or viewbag property defined in the ActionResult method of your Account Controller.

@model QPQ.Web.Models.UserEntity
    ViewBag.Title = "Register";
using (Html.BeginForm()) {
            <div class="editor-label">
                @Html.LabelFor(m => m.Country  )
            <div class="editor-field">
            @Html.ValidationMessageFor(m => m.Country  )
                <input type="submit" value="Go" />

Up Next
    Ebook Download
    View all
    View all