Reader Level:
Articles

MVC Populate Dropdown

By Subal Mishra on July 26, 2012
This example will demonstrate how to populate a dropdown list from a database.
  • 0
  • 0
  • 38500

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

MVC1.jpg



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; }

    [System.Data.Linq.Mapping.Column]
    public string Name { get; set; }

    [System.Data.Linq.Mapping.Column]
    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);
 
       Table
<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>
        <fieldset>
   
            <div class="editor-label">
                @Html.LabelFor(m => m.Country  )
 
            </div>
            <div class="editor-field">
 
            @Html.DropDownList("CountryList")
 
            @Html.ValidationMessageFor(m => m.Country  )
            </div>
            <p>
                <input type="submit" value="Go" />
            </p>
        </fieldset>
    </div>
}

Subal Mishra

A PMP, ITSM certified with Masters degree in the field of Information Technology and Microsoft Certified Professional  with over 11 years of experience in Project Management, System Design, Implementa... Read more

COMMENT USING

Trending up