ASP. NET linkage with Ajax

Source: Internet
Author: User

Database
Create Table [DBO]. [linkage01] (
[ID] [int] identity (1, 1) not null,
[Name] [varchar] (50) Collate chinese_prc_ci_as null
) On [primary]
Go

Create Table [DBO]. [linkage02] (
[ID] [int] identity (1, 1) not null,
[Lid] [int] not null,
[Name] [varchar] (50) Collate chinese_prc_ci_as not null
) On [primary]
Go

Page index. aspx
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "index. aspx. cs" inherits = "_ Index" %>
<HTML>
<Head runat = "server">
<Title> linkagetest. </title>
<Script language = "JavaScript">
// The JB function initializes XMLHTTP Objects Based on Different browsers.
Function JB ()
{
VaR A = NULL;
Try
{
A = new activexobject ("msxml2.xmlhttp ");
}
Catch (E)
{
Try
{
A = new activexobject ("Microsoft. XMLHTTP ");
}
Catch (oc)
{
A = null
}
}
If (! A & typeof XMLHttpRequest! = "Undefined ")
{
A = new XMLHttpRequest ()
}
Return
}

// The following Go function is called when the parent list box is changed. The parameter is the selected entry.
Function go ()
{
VaR svalue = Document. getelementbyid ("ddl01"). value; // obtain the value from the drop-down list in the selection box.
VaR weburl = "index. aspx? Id = "+ svalue; // defines the page for Data Processing
VaR XMLHTTP = JB (); // initialize XMLHTTP objects
XMLHTTP. Open ("get", weburl, true); // submit data. The first parameter is preferably get, and the third parameter is preferably true.
// Alert (XMLHTTP. responsetext );
// If data is successfully returned
XMLHTTP. onreadystatechange = function ()
{
If (XMLHTTP. readystate = 4) // 4 indicates that data is returned successfully.
{
Var result = xmlhttp. responseText; // get the data returned by the server
Document. getElementById ("ddl02"). length = 0; // clear all ddlC drop-down items first
Document. getElementById ("ddl02 "). options. add (new Option ("select", "0"); // add all models to ddlC. Note that Option is not option
If (result! = "") // If the returned data is not empty
{
Var allArray = result. split (","); // splits the received string into arrays according
// Loop this array, note that it starts from 1, because the first character of the received string is, number, so the first array after segmentation is empty
For (var I = 1; I <allArray. length; I ++)
{
Var thisArray = allArray [I]. split ("|"); // splits the string into an array according to |
// Add entries for ddlC
Document. getElementById ("ddl02"). options. add (new Option (thisArray [0]. toString (), thisArray [1]. toString ()));
}
}
}
}
// Send data. Pay attention to the sequence and parameters. The parameter must be null or ""
Xmlhttp. send (null );
}
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>

Province: <select id = "ddl01" name = "ddl01" runat = "server" onchange = "Go (this)"> </SELECT>
City: <select id = "ddl02" name = "ddl02" runat = "server"> </SELECT>
<% --
Save: <asp: dropdownlist id = "ddl01" runat = "server" onchange = "Go (this)"> </ASP: dropdownlist>
City: <asp: dropdownlist id = "ddl02" runat = "server"> </ASP: dropdownlist>
-- %>
<Asp: Button ID = "btnOk" runat = "server" Text = "Confirm" OnClick = "btnOk_Click"/>

</Div>
</Form>
</Body>
</Html>

Class file index. cs
Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;

Public partial class _ index: System. Web. UI. Page
{
Private sqlconnection con;
Private sqldataadapter SDA;
Private sqlcommand cmd;
Private dataset Ds;
Private sqldatareader SDR;

// Database connection string
Public static string constr = "Server =.; database = test; uid = sa; Pwd = sa ";

Protected void page_load (Object sender, eventargs E)
{
Try
{
If (! Ispostback)
{
Con = new SqlConnection (conStr );
Sda = new SqlDataAdapter ("select * from LinkAge01", con );
Ds = new DataSet ();
Sda. Fill (ds, "LinkAge01 ");
Ds. Tables ["LinkAge01"]. DefaultView. Sort = "id asc ";
Ddl01.DataSource = ds. Tables ["LinkAge01"]. DefaultView;
Ddl01.DataValueField = "id ";
Ddl01.DataTextField = "name ";
Ddl01.DataBind ();
}
Response. Write ("Request. Form [ddl02]:" + Request. Form ["ddl02"] + "<br/> ");
BindDrop ();
}
Catch (Exception ex)
{
Response. Write ("error:" + ex. ToString ());
}
}

Protected void btnOk_Click (object sender, EventArgs e)
{
Try
{
Response. Write (ddl01.Items [ddl01.SelectedIndex]. Text + "<br/> ");
Response. Write (ddl02.Items [ddl02.SelectedIndex]. Text + "<br/> ");
}
Catch (Exception ex)
{
Response. Write ("error:" + ex. ToString ());
}
}

Protected void BindDrop ()
{
String str = Request. QueryString ["id"];
String str1 = ddl01.Items [ddl01.SelectedIndex]. Value;
Response. Write ("str1 =" + str1 + "<br/> ");
String a = str + "abc ";
If (str + "abc "! = "Abc") // If str is added with a string! = The original string indicates that the onchange event of ddlS has been triggered.
Bindchild (STR); // triggers the onchange event of ddls.
Else
Bindparent (str1); // The first time a live refresh is loaded
}

Protected void bindparent (string str1)
{
Try
{
// If this is the first request or the page is refreshed, select the value of ddls.
// Convert the parameter to int
Int I = convert. toint32 (str1 );
Ddl02.items. Clear ();
Ddl02.Items. Add (new ListItem ("select", "0 "));
Con = new SqlConnection (conStr );
Cmd = new SqlCommand ("select * from LinkAge02 where lID =" + I, con );
Con. Open ();
Sdr = cmd. ExecuteReader ();
While (sdr. Read ())
{
Ddl02.Items. Add (new ListItem (sdr ["name"]. ToString (), sdr ["id"]. ToString ()));
}
SDR. Close ();
Con. Close ();
Ddl02.items [0]. Selected = true;
Ddl01.items [0]. Selected = false;
// Add the following statement to save the status of the second ddl02 when you click the submit button to submit the form.
Response. Write ("request. Form [ddl02]:" + request. Form ["ddl02"] + "<br/> ");
Ddl02.value = request. Form ["ddl02"];

}
Catch (Exception ex)
{
Response. Write ("error:" + ex. ToString ());
}
}

Protected void BindChild (String str)
{
// The content added to any controls including dropdownlist through js will not be saved
// Convert the parameter to int
Int I = Convert. ToInt32 (str );
String result = "";
Response. Clear ();
Con = new SqlConnection (conStr );
Cmd = new SqlCommand ("select * from LinkAge02 where lID =" + I, con );
Con. Open ();
Sdr = cmd. ExecuteReader ();
While (sdr. Read ())
{
Result + = "," + sdr ["name"]. ToString () + "|" + sdr ["id"]. ToString ();
}
Sdr. Close ();
Con. Close ();
Response. Write (result );
Response. Flush ();
Response. Close ();

}
}

Address: http://blog.csdn.net/mathew3625/archive/2008/04/13/2288707.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.