Introduction:
Here I will explain how to set default selected value for dropdownlist in asp.net mvc razor with example or asp.net mvc @Html.Dropdownlist set default selected value in razor with example or asp.net mvc set dropdownlist selected value with example. In asp.net mvc by using @Html.Dropdownlist or @Html.DropdownlistFor properties we can implement dropdownlist and we can easily set dropdownlist default selected value using @Html.Dropdownlist property.
Description:
In previous articles I explained asp.net mvc create image gallery with example, asp.net mvc create rdlc report with example, asp.net mvc get dropdownlist selected value example, asp.net mvc set urls for action methods 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 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 set default selected value for dropdownlist in asp.net mvc with example.
In previous articles I explained asp.net mvc create image gallery with example, asp.net mvc create rdlc report with example, asp.net mvc get dropdownlist selected value example, asp.net mvc set urls for action methods 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 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 set default selected value for dropdownlist in asp.net mvc with example.
To
set dropdownlist default selected value in asp.net
mvc we
will write the code like as shown below
@Html.DropDownList("ddlUsers", new SelectList(Model.usersinfo, "UserId", "UserName", 2), "Select User")
|
Here
“DropDownList” function will render it as
<select> with <options> tags and “ddlUsers” is used to set id and name
for dropdownlist and “Model.usersinfo”
will provide all possible options for dropdown and “2” will set default selected value for dropdownlist. Once above
dropdown render into html browser that will be like as shown below.
<select id="ddlUsers" name="ddlUsers">
<option value="">Select User</option>
<option value="1">Suresh Dasari</option>
<option selected="selected" value="2">Rohini Alavala</option>
<option value="3">Praveen Kumar</option>
<option value="4">Madhav Sai</option>
</select>
|
If
you observe above rendered code by default dropdownlist value “2” selected.
We
will see how to bind dropdownlist values from database and how to set dropdownlist
default 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
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 & 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.DropDownList("ddlUsers",
new SelectList(Model.usersinfo,
"UserId", "UserName",
2), "Select User")<br
/><br
/>
Selected Text: <label
id="lbltxt"></label><br
/><br
/>
Selected Value: <label
id="lblid"></label>
</div>
<script
type="text/javascript">
$(function
() {
if
($("#ddlUsers").val()
> 0)
{
$("#lbltxt").text($("#ddlUsers
option:selected").text());
$("#lblid").text($("#ddlUsers").val());
}
//Dropdownlist
Selectedchange event
$('#ddlUsers').change(function
() {
// Get Dropdownlist
seleted item text
$("#lbltxt").text($("#ddlUsers
option:selected").text());
// Get Dropdownlist
selected item value
$("#lblid").text($("#ddlUsers").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
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. |
|||
|
|||
1 comments :
Hey Suresh, you do a great job going through the code and making it easy to understand while providing a useful solution. Thanks for this.
Note: Only a member of this blog may post a comment.