Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
434 views

MVC Bind (Populate) Dropdownlist From Database With Example - ASP - NET, C#.NET, VB - NET, JQuery, JavaScript, Gridview PDF

Uploaded by

arsenr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
434 views

MVC Bind (Populate) Dropdownlist From Database With Example - ASP - NET, C#.NET, VB - NET, JQuery, JavaScript, Gridview PDF

Uploaded by

arsenr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

From Cloud Shell

Google Cloud commands and


deploying your rst VM,
Platform training to running apps on GKE

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

microsoft excel tutorial sql query examples

open source software visual studio code

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.

Column Name Data Type Allow Nulls

userid Int(IDENTITY=TRUE) NO

username varchar(50) Yes

education Varchar(50) Yes

location Varchar(50) Yes


Saveti iskusnog freelancera
Or use following query to create userdetails table in database and insert some data to bind values to
Kako da se dobro predstavite i
dropdownlist. pronađete prave klijente za svoj
freelance posao.

create table userdetails(


userid int primary key identity,
username varchar(50),
education varchar(50),
location varchar(50) how to bind
dropdownlist in
) asp.net using…

INSERT INTO userdetails(username,education,location) Show Bind Data


values('Suresh Dasari','B.Tech','Chennai'), to Asp.net
Dropdownlist…
('Rohini Alavala','Msc','Guntur'),
('Praveen Kumar','B.Tech','Bangalore'), Import/Upload
('Madhav Sai','MBA','Nagpur') Excel Data to
Asp.net…

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

Step By Step Tutorials

Asp.Net MVC Tutorial

C# Tutorial

SQL Server Tutorial

AngularJS Tutorial

LINQ Tutorial

Android Tutorial

iOS Tutorial

Swift Tutorial

SQLite Tutorial

Font Icons Tutorial


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

Get Latest articles in your inbox for free.

Enter your email address:

Subscribe

Aspdotnetsuresh
16,784 likes

Like Page Contact Us

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; }
}
}

SQL Server Connectivity


Data Access Components

Cross-Platform Solution for Delphi, C+


+Builder, and Lazarus. Download SDAC
Now!
devart.com

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.

Subscribe by RSS Subscribe by Email

6 comments :

Anonymous said...
1
works

April 17, 2017 at 5:31 AM

nilesh tayde said...


2
very useful article

February 28, 2018 at 4:14 AM

pagol chagol said...


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

March 1, 2018 at 11:02 AM

Anonymous said...
4
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.]

May 23, 2018 at 8:45 AM

Naveen Reddy said...


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

September 10, 2018 at 7:37 AM

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.

February 17, 2019 at 11:03 PM

Give your Valuable Comments

Enter your comment...

Comment as: Google Accoun

Publish Preview

Newer Post Home Older Post

Subscribe to: Post Comments ( Atom )

Other Related Posts

Interview Questions in ASP.NET,C#.NET,SQL Server,.NET Framework

Simple login form example in asp.net Check Username and Password availability in database

Asp.net insert, Edit, update, delete data in gridview

3 tier architecture example in asp.net with C#

Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

Best Login Page Design in HTML, CSS with Source Code

OOPS (Object Oriented Programming) Concepts in C#.NET with Examples

C# - Constructors in C# with Example, Types of Constructor in C# with Example

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

© 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.

You might also like