SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by Lion Articles | ASP.NET Programming November 01, 2010
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.
Reader Level:
Download Files:
 

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;
    }
}


 

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor