Introduction: In
this article I have explained how we can Populate Dropdown List dynamically
using Asp.net MVC Razor
Description:
In the previous article I have explained Code First migration in asp.net MVC 4, Create, Read, Update and Delete in Asp.net with MVC 4 Razor view Engine using Entity framework with Code first approach, What is Scaffolding in Asp.net MVC? and What is Asp.net MVC? Its advantages and disadvantges.
In the previous article I have explained Code First migration in asp.net MVC 4, Create, Read, Update and Delete in Asp.net with MVC 4 Razor view Engine using Entity framework with Code first approach, What is Scaffolding in Asp.net MVC? and What is Asp.net MVC? Its advantages and disadvantges.
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:
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:
Write the code on Index.cshtml:
@using (Html.BeginForm())
{
@Html.DropDownList("department", "--Select One--");
}
Build the project and run.
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.
Hey! Can you upload this code please?
ReplyDelete