Populate Dropdown List dynamically using Asp.net MVC Razor - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial


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.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+
loading...

1 comments:

Hey! Can you upload this code please?


EmoticonEmoticon