Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Asp.Net MVC Bind (Populate) Dropdownlist from Database with Example

Oct 19, 2016
Introduction

Here I will explain how to bind dropdownlist from database in
asp.net mvc with example or asp.net mvc populate dropdownlist from database with example or asp.net mvc fill dropdownlist values from database with example or asp.net mvc bind dropdownlist from database and get dropdownlist selected with example. In asp.net mvc by using @Html.Dropdownlist or @Html.DropdownlistFor properties we can easily implement dropdownlist based on the values from database.


In asp.net mvc we can implement dropdownlist by using two properties either @Html.DropDownList model or @Html.DropDownListFor model. Before we start implementing first design userdetails table in database and insert some data like as shown below.

Column Name
Data Type
Allow Nulls
userid
Int(IDENTITY=TRUE)
NO
username
varchar(50)
Yes
education
Varchar(50)
Yes
location
Varchar(50)
Yes
Or use following query to create userdetails table in database and insert some data to bind values to dropdownlist.


create table userdetails(
userid int primary key identity,
username varchar(50),
education varchar(50),
location varchar(50)
)

INSERT INTO userdetails(username,education,location)
values('Suresh Dasari','B.Tech','Chennai'),
('Rohini Alavala','Msc','Guntur'),
('Praveen Kumar','B.Tech','Bangalore'),
('Madhav Sai','MBA','Nagpur')

Once we create userdetails table now create asp.net mvc application for that Open visual studio --> Go to File --> Select New --> Project like as shown below

Once we select Project new popup will open in that select Asp.Net Web Application and give name to application and click OK like as shown below

Once click OK new popup will open in that select Empty template and select folders and core reference as MVC and click OK like as shown below

Once we finished creating application our project structure will be like as shown below

Now we will add new model to our application to define properties in our application for that right click on Models folder --> select Add --> select Class like as shown below

Once we click on Class new popup will open in that give name of your model as “UserDetails” and click Add button like as shown below.

Now open newly created model (UserDetails) and write the code like as shown below


using System.Collections.Generic;

namespace InsertGetUserDetails.Models
{
public class UserDetails
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Education { get; set; }
public string Location { get; set; }
public List<UserDetails> usersinfo { get; set; }
}
}

Now we will add new controller to get data from database for that right click on Controller folder --> select Add --> Controller like as shown below

Adding new controller to asp.net mvc application
Once we click on Controller new popup will open in that select MVC 5 Controller – Empty and click Add like as shown below.

select empty mvc controller to add it in asp.net mvc application
Once click on Add new window will open in that enter name of controller and click Add like as shown below

Now open newly created controller and write the code like as shown below


using MVCExamples.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

namespace MVCExamples.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
UserDetails objuser = new UserDetails();
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySamplesDB"))
{
using (SqlCommand cmd = new SqlCommand("select * from userdetails", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
List<UserDetails> userlist = new List<UserDetails>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
UserDetails uobj = new UserDetails();
uobj.UserId = Convert.ToInt32(ds.Tables[0].Rows[i]["userid"].ToString());
uobj.UserName = ds.Tables[0].Rows[i]["username"].ToString();
uobj.Education = ds.Tables[0].Rows[i]["education"].ToString();
uobj.Location = ds.Tables[0].Rows[i]["location"].ToString();
userlist.Add(uobj);
}
objuser.usersinfo = userlist;
}
con.Close();
}
return View(objuser);
}
}
}

If you observe above controller code, we are getting user details from database.

Now we will add view to our controller action method for that right click on Index action method --> select Add View like as shown below

Now give name “Index” to view, select template as “Empty” and select Model class as “UserDetails” which we created in our application then click on Add button like as shown below

 The newly created view will be added under Views folder like as shown below

Now open newly created view and write the code like as shown below


@model MVCExamples.Models.UserDetails

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Bind DropdownList Details</title>
</head>
<body>
<div>
Select User: @Html.DropDownListFor(m => m.UserId, new SelectList(Model.usersinfo, "UserId", "UserName"), "Select User")
</div>
</body>
</html>

Now we will run and see the application result. (url always in the format of http://localhost:portnumber/controller name/action method name) and check the output that would be like as shown below


Bind dropdownlist in asp.net mvc from database with example
This is how we can bind dropdownlist in our asp.net mvc applications based on requirement.

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

6 comments :

Anonymous said...

works

nilesh tayde said...

very useful article

Unknown said...

How can add search option or bootstrap class in @html.dropdownlist

Anonymous said...

Good article but it fails for me at this point:

@Html.DropDownListFor(m => m.UserId, new SelectList(Model.usersinfo, "UserId", "UserName"), "Select User")

Error is [NullReferenceException: Object reference not set to an instance of an object.]

Unknown said...

if i want to save the value to database which name i can call where i can add name like txtuser

Hi Suresh,It is a useful article.If i need to bind more than one dropdown list in one page from database what should i do.please suggest. said...

Hi Suresh,It is a useful article.If i need to bind more than one dropdown list in one page from database what should i do.please suggest.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.