- Get link
- X
- Other Apps
Posted by
Real
- Get link
- X
- Other Apps
Hello Guys,
Today I am going to share, how you can make two ASP.NET Dropdown List in a cascading manner. That's means once you have selected an Item from First Dropdown, the other related Dropdown will get populated with the Item related to the first one.
Generally, we can achieve this by OnSelectedIndexChanged but this will make a full Post back to the Server and Page will get an update and if there are lots of controls like Editors and other heavy controls on the page then it will take a long time to load the whole page again to the client. Which is really doesn't look good. So I came up with a solution to do Ajax post which can do an async call to the server and full-page Postback will not take place any more.
Below are the code snippets for Cascading DropdownList:
ASPX PAGE (*.aspx):
<body>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>Cascading DropDown</legend>
<asp:DropDownList ID="ddlDestn" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="(Please Select)" Value="0" Selected="True" />
</asp:DropDownList>
<asp:DropDownList ID="ddlHotels" runat="server">
</asp:DropDownList>
</fieldset>
</div>
</form>
</body>
So Now we are done with the designer part of the webpage. Now we need to write class for getting List of related Data selected from first DropDownList.
I am having two tables in SQL SERVER 2008 DATABASE:
1. Destinations Table which Includes (Kochi, Munnar, Hyderabad)
2. Hotels Table which Includes the related data (I mean the hotels exists at the selected destination.)
Below are are the Screen Shots of the tables:
I believe scripts for creating this type of small tables is not required right? (I am little lazy to write
)
Thanking to Chetna for Identifying that I missed BAL class which is required to get data from the DB. Below I am providing the same.
First we need to create a BAL class like BAL.cs which is our DataLayer class.
Class BAL (Business Access Layer ): (BAL.cs)
public DataTable GetDataTable(string tblName)
{
dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connStr))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
string sql = "Select * from " + tblName;
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
da.Dispose();
}
return dt;
}
We can access this class by just creating the instance(Object) of this class. For example : var bl = new BAL();
Now we need to get this data in our Code Behind pages.
ASPX.CS : (*.aspx.cs)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var bl = new BAL();
ddlDestn.DataSource = bl.GetDataTable("tbl_Place");
ddlDestn.DataTextField = "Place";
ddlDestn.DataValueField = "Id";
ddlDestn.DataBind();
}
}
[WebMethod]
public static List<Hotels> FetchHotels(int id)
{
var hotels = new Hotels();
return hotels.FetchHotels(id);
}
Here you can see I have written WebMethod ( using System.Web.Services; ) on the top of the function, actually for calling any code behind methods by JavaScript (Jquery) we need to add this.
Now we need to create a class Hotels for Fetching the Hotels by selecting the Id from first DropDownList.
CLASS : (Hotels.cs)
public class Hotels
{
public int Id { get; set; }
public string HotelName { get; set; }
private static List<Hotels> LoadData()
{
List<Hotels> lst = new List<Hotels>();
DataTable dt = new DataTable();
var bl = new BAL();
dt = bl.GetDataTable("tbl_Hotel");
foreach (DataRow dr in dt.Rows)
{
lst.Add(new Hotels { Id = Convert.ToInt32(dr["PId"]), HotelName = Convert.ToString(dr["HotelName"]) });
}
return lst;
}
public List<Hotels> FetchHotels(int id)
{
return (from a in LoadData()
where a.Id == id
select a).ToList();
}
}
Now we are all done with the C# Code behind part, here is the most Important part for calling these Method by Ajax. For this we can use Jquery Ajax post Method, Below are the syntaxes:
JQUERY :(AJAX POST)
<script src="js/jquery-1.10.0.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(function () {
var $ddl = $("select[name$=ddlDestn]");
var $ddlCars = $("select[name$=ddlHotels]");
$ddl.focus();
$ddl.bind("change keyup", function () {
if ($(this).val() != "0") {
loadHotels($("select option:selected").val());
$ddlCars.fadeIn("slow");
} else {
$ddlCars.fadeOut("slow");
}
});
});
function loadHotels(selectedItem) {
$.ajax({
type: "POST",
url: "Default.aspx/FetchHotels",
data: "{id: " + selectedItem + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function Success(data) {
printHotels(data.d);
}
});
}
function printHotels(data) {
$("select[name$=ddlHotels] > option").remove();
for (var i = 0; i < data.length; i++) {
$("select[name$=ddlHotels]").append(
$("<option></option>").val(data[i].Id).html(data[i].HotelName)
);
}
}
</script>
That's it now you can Download the latest Jquery by clicking this URL: LATEST JQUERY DOWNLOAD
Download Link for this Sample: CASCADING DROPDOWN
Working Sample Screen:
Cheers. If you like the post please share by any of the below Social network and give a Plus one in Google Plus .
Regards,
Anand Tiwari.
- Get link
- X
- Other Apps
Comments
Thank you Anand, I was searching for this functionality and here I got. This one has helped me in my project.
ReplyDeleteThanks again.
var bl = new BAL();
ReplyDeletehello..
i m getting a error in the above written line. Need help.
Thanks in Advance
Dear Chetna,
ReplyDeleteI appreciate you valuable comment and thanking you to Identify the error in code.
Actually bl is a instance of BAL (Business Access Layer Class), I should provide the same in the code, here by I am updating the Post please have a look.
Keep visiting I'll try to help as much as I can :).
muye buenoo
ReplyDeleteGracias Alvaro
ReplyDeleteunable to get select value in server side for state dropdown.please help me .
ReplyDeletePossible error is you are missing If(!page.IsPostBack) in PageLoad event, Kindly check your code once and let me know.
ReplyDeletebuenisimo
ReplyDeleteHi
ReplyDeleteThe above code has been very useful, for which I am thankful.
But I get a problem as I try to access the column "Id" from the chosen Hotel (in the "second" ddl).
It is clear in the code that the value given to the second ddl options are all the same value (i.e. PId), so the second ddl returns the same value for all options.
How can this be addressed?
Hello i need the javascript to bind the asp.net listview using this technique...! what i want is when i click on dropdownlist then listview should be bind behalf of a selected value of dropdownlist
ReplyDeleteThanks you ..... very useful code ... :)
ReplyDelete