How to Bind Dropdown list using JSON, jQuery in ASP.NET 3.5


JSON (JavaScript Object Notation) is a lightweight data-interchange format. For more information About JSON Please see http://www.json.org/

jQuery is a library that makes it quicker and easier to build JavaScript webpages and web application.

The jQuery library actually comes in 2 forms.

  1. Uncompressed .js
  2. Minified .js

For more information about jQuery and its plugin http://plugins.jquery.com/

In this project we use Newtonsoft.Json library makes working with JavaScript and JSON formatted data in .NET simple. Quickly read and write JSON using the JsonReader and JsonWriter or serialize your .NET objects with a single method call using the JsonSerializer.

For more Information about Json.NET http://json.codeplex.com/

Your aspx Page like

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
htmlxmlns="http://www.w3.org/1999/xhtml">
<
headrunat="server">
<
title>JSON Example By Jayendra</title>
<styletype="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 64px;
        }
</style>

<scriptlanguage="javascript"type="text/javascript"src="JScript/jquery-1.2.6.js"></script>

<scripttype="text/javascript">
        $(document).ready(function() {
            $('#<%=ddlState.ClientID %>').change(function() {
var id = $('#<%=ddlState.ClientID %>').val();
if (id != "--Select State--") {
                    $('#<%=ddlCity.ClientID %>').html("");
                    $.getJSON("Responce.aspx?id=" + id, function(citys) {
                    $.each(citys, function() {                         
                            $('#<%=ddlCity.ClientID %>').append($("<option></option>").val(this['ID']).html(this['CityName']));
                        });
                    });
                }
            });
             $('#<%=ddlCity.ClientID %>').change(function() {
var cityid = $('#<%=ddlCity.ClientID %>').html();
                alert(cityid);
            });

        });
</script>

</head>
<
body>
<
formid="form1"runat="server">
<
div>
<
tableclass="style1">
<
tr>
<
tdclass="style2">
                    State:
</td>
<
td>
<
asp:DropDownListID="ddlState"runat="server">
</
asp:DropDownList>
</
td>
</
tr>
<
tr>
<
tdclass="style2">
                    City:
</td>
<
td>
<
asp:DropDownListID="ddlCity"runat="server">
</
asp:DropDownList>
</
td>
</
tr>
</
table>
</
div>
</
form>
</
body>
</
html>

Your .cs file

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

publicpartialclass_Default : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
    {
if (!IsPostBack)
        {
            FillStateDropdownlist();
            ddlCity.Items.Insert(0,"--Select City--");
        }
    }

privatevoid FillStateDropdownlist()
    {
using(DataClassesDataContext db = newDataClassesDataContext())
        {
var info = from p in db.States
orderby p.ID
select p;
if(info != null&& info.Count() > 0)
            {
                ddlState.DataSource = info;
                ddlState.DataTextField = "StateName";
                ddlState.DataValueField = "ID";
                ddlState.DataBind();
            }
            ddlState.Items.Insert(0, "--Select State--");                      
        }
    }
}

For binding city dropdownlist we use Response page.

Your response page .cs files as under.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;

 publicpartialclassResponce : System.Web.UI.Page
{
    #region City Class
privateclassCitys
    {
publicint ID { get; set; }
publicstring CityName { get; set; }
    }
    #endregion
List<Citys> citylist = newList<Citys>();
protectedvoid Page_Load(object sender, EventArgs e)
    {

if (Request["id"] != null&& Request["id"].ToString() != "")
            {

                Response.Clear();
                Response.Write(GetCity(Convert.ToInt32(Request["id"].ToString())));
                Response.End();

            }

    }

privatestring GetCity(int StateID)
    {

using (DataClassesDataContext db = newDataClassesDataContext())
        {
var info = from p in db.Cities
where p.StateID.Equals(StateID)
orderby p.ID
//select p;
selectnew {
                           p.ID,
                           p.CityName
                       };
 
if (info != null&& info.Count() > 0)
            {
Citys myCity1 = newCitys();
                myCity1.ID = 0;
                myCity1.CityName = "--Select CityName--";
                citylist.Add(myCity1);
foreach (var item in info)
                {
Citys myCity = newCitys();
                    myCity.ID = item.ID;
                    myCity.CityName = item.CityName.Trim();
                    citylist.Add(myCity);                  
                }  
            }        
        }

string json = JsonConvert.SerializeObject(citylist, Formatting.Indented);

return json;
    }
}


 

Up Next
    Ebook Download
    View all
    Learn
    View all