Thursday, January 2, 2014

Populate Dropdown List dynamically using Asp.net MVC Razor

Introduction: In this article I have explained how we can Populate Dropdown List dynamically using Asp.net MVC Razor
Populate Dropdown List

Here I want to populate the dropdown list to show Departments of Employee. I have a table Department:

DepartmentId
Int(primary key& Auto increment)

DepartmentName
nvarchar(MAX)

I add an Empty Controller to Project. Add the namespace of project models to controller:
using MVCAPPLICATION.Models;

Here my project name is MVCAPPLICATION. After that write the code:
private ProjectContext db = new ProjectContext();

        public ActionResult Index()
        {
            ViewBag.department = new SelectList(db.Departments, "DepartmentId", "DepartmentName");
            return View();
        }

ProjectContext is the DbContext of project.
Now add a view for index. To add view Right click on Index>>Add view. Window pop up will be open and follow the instruction as show in attached snapshot:

Populate Dropdown List

Write the code on Index.cshtml:
@using (Html.BeginForm())
{
    @Html.DropDownList("department", "--Select One--");
}

Build the project and run.

Is this article helpful for you?

If yes post your comment to appreciate my work and fell free to contact me. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

1 comment: