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 Get DropdownList Selected Value in Razor

Oct 24, 2016
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.


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 <select> with <options> 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 id="UserId" name="UserId">
<option value="">Select User</option>
<option value="1">Suresh Dasari</option>
<option value="2">Rohini Alavala</option>
<option value="3">Praveen Kumar</option>
<option value="4">Madhav Sai</option>
</select>

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


<script type="text/javascript">
$(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());
})
})
</script>


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<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 & Get Selected Value</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
Select User: @Html.DropDownListFor(m => m.UserId, new SelectList(Model.usersinfo, "UserId", "UserName"), "Select User")<br /><br />
Selected Text: <label id="lbltxt"></label><br /><br />
Selected Value: <label id="lblid"></label>
</div>
<script type="text/javascript">
$(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());
})
})
</script>
</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



Asp.Net MVC Get DropdownList Selected Value in Razor 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

1 comments :

Dnyaneshwar Sable said...

Dear sir,

very valuable information..

Give your Valuable Comments

Other Related Posts

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