ARTICLE

MVC Populate Dropdown

Posted by Subal Mishra Articles | ASP.NET MVC with C# July 26, 2012
This example will demonstrate how to populate a dropdown list from a database.
Reader Level:

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

Login to add your contents and source code to this article
post comment
     

great job

Posted by twp saddam Oct 20, 2012

great job.....

Posted by twp saddam Oct 20, 2012

Richa, for Linq to SQL yes...

Posted by Subal Mishra Jul 26, 2012

Is it is necessary to use the lamda expression when I use any controls like textbox,label etc in Razor view?

Posted by Richa Garg Jul 26, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts