MVC dropdownlist selected value

Introduction:

Here I will explain how to get dropdownlist selected value in
asp.net mvc razor with example or asp.net mvc get selected value from dropdownlist in razor with example or asp.net mvc bind dropdownlist values from database and get dropdownlist selected value with example. In asp.net mvc by using @Html.Dropdownlist or @Html.DropdownlistFor properties we can easily implement dropdownlist by binding values from database and we can get dropdownlist selected values by using id values.

Description:

In previous articles I explained asp.net mvc bind dropdownlist values from database, asp.net mvc redirect to another view or controller action method, asp.net mvc tightly coupled view in application with example, difference between asp.net web api and web service with example, web api in asp.net and consume web api in asp.net with example, asp.net mvc show alert message after post data, asp.net mvc insert data into database with example
and many articles relating to asp.net mvc, asp.net, c#,vb.net. Now I will explain how to get dropdownlist selected value in asp.net mvc with example.

Generally, to bind dropdownlist in asp.net mvc we will write the code like as shown below


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

Here DropDownListFor function will render it as with tags and m =>m.UserId is used to retrieve selected value and Model.usersinfo will provide all possible options for dropdown. Once above dropdown render into html browser that will be like as shown below.


Select User
Suresh Dasari
Rohini Alavala
Praveen Kumar
Madhav Sai

In jQuery by using dropdownlist id we can easily get selected value in asp.net mvc like as shown below.


$[function [] {
//Dropdownlist Selectedchange event
$['#UserId'].change[function [] {
// Get Dropdownlist seleted item text
$["#lbltxt"].text[$["#UserId option:selected"].text[]];
// Get Dropdownlist selected item value
$["#lblid"].text[$["#UserId"].val[]];
}]
}]


We will see how to bind dropdownlist values from database and how to get dropdownlist selected value with example in asp.net mvc.

Generally, 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 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

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 userlist = new List[];
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;
}

Bind DropdownList Details & Get Selected Value
Select User: @Html.DropDownListFor[m => m.UserId, new SelectList[Model.usersinfo, "UserId", "UserName"], "Select User"]
Selected Text:
Selected Value:
$[function [] {
//Dropdownlist Selectedchange event
$['#UserId'].change[function [] {
// Get Dropdownlist seleted item text
$["#lbltxt"].text[$["#UserId option:selected"].text[]];
// Get Dropdownlist selected item value
$["#lblid"].text[$["#UserId"].val[]];
}]
}]


Now we will run and see the application result. [url always in the format of //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

Video liên quan

Chủ Đề