MVC Bind (Populate) Dropdownlist From Database With Example - ASP - NET, C#.NET, VB - NET, JQuery, JavaScript, Gridview PDF
MVC Bind (Populate) Dropdownlist From Database With Example - ASP - NET, C#.NET, VB - NET, JQuery, JavaScript, Gridview PDF
ASP.NET,C#.NET,VB.NET,JQuery,
HOME ASP.NET AJAX GRIDVIEW JAVASCRIPT SQL JQUERY OOPS CONCEPTS MVC INTERVIEW QUESTIONS TRACE MOBILE TUTORIALS
JavaScript,Gridview
aspdotnet-suresh offers C#.net articles and
tutorials,csharp dot net,asp.net articles and
Search This Site
examples of asp.net 2.0 /3.5,AJAX,SQL ServerDropdownlist
Asp.Net MVC Bind (Populate) from Database with
tutorials,VB.NET Articles,Gridview articles,code
Example of .net technologies
Articles,examples
Custom Searc
By: Suresh Dasari Oct 19, 2016
Categories: asp.net mvc , DropdownList , mvc
SPONSORED SEARCHES
0 Introduction:
Like
Share
Here I will explain how to bind dropdownlist from database in asp.net mvc with example or asp.net mvc
Tweet
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
Share example. In asp.net mvc by using @Html.Dropdownlist or @Html.DropdownlistFor properties we
can easily implement dropdownlist based on the values from database.
Description:
Follow US
In previous articles I explained asp.net mvc tutorial with examples, asp.net mvc action verbs with
SURE SH DASARI
example, html helpers in asp.net mvc with examples, asp.net mvc redirect to another view or controller
VI EW MY COMPLETE PROFILE
action method, asp.net mvc show alert message after post data, asp.net mvc insert data into database
with example, asp.net mvc tightly coupled view in application with example, and many articles relating
to asp.net mvc, asp.net, c#,vb.net. Now I will explain how to bind or populate dropdownlist from
database in asp.net mvc with example.
SharePoint Data Integration
Ad Take advantage of the freedom,
flexibility and power of the SSIS ETL…
KingswaySoft
Learn more
Select Language
In asp.net mvc we can implement dropdownlist by using two properties either @Html.DropDownList Powered by Translate
model or @Html.DropDownListFor model. Before we start implementing first design userdetails table
in database and insert some data like as shown below.
userid Int(IDENTITY=TRUE) NO
Once we create userdetails table now create asp.net mvc application for that Open visual studio --> Go Asp.Net MVC
to File --> Select New --> Project like as shown below Set
DropdownList…
Dropdownlist
Validation using
JavaScript in…
jQuery Set
Dropdownlist
Selected Value…
Set
Dropdownlist
Selected Value…
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
C# Tutorial
AngularJS Tutorial
LINQ Tutorial
Android Tutorial
iOS Tutorial
Swift Tutorial
SQLite Tutorial
Subscribe
Aspdotnetsuresh
16,784 likes
Once we finished creating application our project structure will be like as shown below Be the first of your friends to like this
Tags
Asp.net JQuery C#.Net General VB.NET
Code Snippets Javascript SQL Server
Gridview asp.net mvc c# JQuery Plugins
Errors Interview Questions Fileupload Ajax mvc
DropdownList AngularJS JSON validations Google API
AutoComplete Google MAPS CSS DatePicker Windows
Application IISServer Modalpopup Membership
Authentication CheckBox Crystal Reports HTML
ExcelSheet OOPS Concepts SharePoint jQuery UI
ExportGridviewData XML SendMail WebService Entity
Framework UpdatePanel AjaxModalPopupExtender Bootstrap
Google Maps API InternetTips SlideShow ToolTip Visual
Studio WCF Menu Progressbar Razor View SQL Joins
Now we will add new model to our application to define properties in our application for that right click web.config ADO.NET DataGridview Repeater Web API
on Models folder --> select Add --> select Class like as shown below YouTube AjaxAsyncFileUpload Cookie DataList
EncryptionandDecryption LightBoxEffect RDLC Report
RadioButtonList Windows Service loading Image Accordion
Menu Charts CheckBoxList Dynamic Controls Facebook
Fixed Header on Scroll Generic List Global.asax IEnumerable
SSRS Twitter jQuery Menu Access Database Blog Statistics
KeyBoard Key Codes ListBox MultilineTextbox Polymorphism
UI Grid ZIP UNZIP Files jQuery Cookie setInterval setTimeOut
360 Degree View Plugins ASP AjaxAutoCompleteExtender
AjaxTabContainer Average rating Captcha Flip Effect HTML5 Installer
LINQ Linkedin MySQL News Ticker in jQuery PDF Viewers Product
Reviews QR Code QueryString Reflection Resize Image Reviews
SQL Constraints SQL Server 2008 R2 Session Timeout SiteMap
Social Media Bookmark Plugins ThumbnailsGeneration UserName
Check Visitors Count Windows 8 app.config asp.net core jQuery
Media Plugins sorting windows 10 3-TierArchitecture
AbstractVsInterface ActiveDirectory Advertise Ajax Calendarextender
Ajax ConfirmbuttonExtender AjaxAccordionControl
AjaxCalendarExtender AjaxCollapsiblePanelControl
AjaxDragPanelExtender AjaxPasswordStrength AjaxRatingControl
Once we click on Class new popup will open in that give name of your model as “UserDetails” and click AjaxSlideshowExtender Arraylist Assembly Authorization Caching
Add button like as shown below. Chatting Plugins CodingStandards Containers Custom Right Click
Menu Dapper DataGrid Docker Donate Error Log Forums Google
Charts Gzip Compression Hyperlinks IP Address ImportContacts Lync
MCC Award MVP Award Northwind Database Notification Bar
Panorama Image Viewer Plugins Print DIV Projects Query Strings
RSSFeeds Read/Write text file ReadOnlyValues RichTextBox
Scrollbar Session Setup File Spell Checker TFS Testimonial Example
Testing TextArea Trace Mobile Number Try Catch VBScript Virtual
Keyboard WPF bulk copy code contactus delegates dynamically page
create generate script jQuery Audio Plugins jQuery Mobile jQuery
Video Plugins jqGridview scroll top/bottom of div slider from folder
tree view
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; }
}
}
OPEN
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
Once we click on Controller new popup will open in that select MVC 5 Controller – Empty and click Add
like as shown below.
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
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.
6 comments :
Anonymous said...
1
works
Anonymous said...
4
Good article but it fails for me at this point:
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...
6
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.
Publish Preview
Simple login form example in asp.net Check Username and Password availability in database
Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example |
WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for Beginners
how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save
and retrieve images from database using asp.net