Maybe "excellent" will bring a lot of criticism, but I think it is really good. I looked at about 20 linked drop-down lists without refreshing, and they were a mess under Firefox. I almost made two for this. Oh my god, how to keep the value of the second list box after submitting the form, because if you add entries to the drop-down box through js, its state will not be saved. Test platform: ie6, firefox
Function: Second level non-refresh linkage Features: Cross-browser; submit the form to get the value of the second drop-down box; data comes from the database; use xmlhttp to send requests to achieve non-refresh requests: If you can find a better method, please Tell me, thank you very much, your criticism and suggestions are a great encouragement to me
webform1.aspx:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="drop.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content=" http://schemas.microsoft.com/intellisense/ie5 ">
<script language="javascript">
//The jb function will initialize an xmlhttp object according to 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 A
}
//The following Go function is called when the parent list box changes, and the parameter is the selected item.
function Go(obj)
{
//Get the value of the drop-down list of the selection box
var svalue = obj.value;
//Define the page to process data
var weburl = "webform1.aspx?parent_id="+svalue;
//Initialize an xmlhttp object
var xmlhttp = jb();
//Submit data, the first parameter is preferably get, and the third parameter is preferably true
xmlhttp.open("get",weburl,true);
// alert(xmlhttp.responseText);
//If the data has been returned successfully
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)//4 represents successful return of data
{
var result = xmlhttp.responseText;//Get the data returned by the server
//First clear all drop-down items of dListChild
document.getElementById("dListChild").length = 0;
//Add all models to dListChild. Note that Option is not option.
document.getElementById("dListChild").options.add(new Option("All models","0"));
if(result!="")//If the returned data is not empty
{
//Split the received string into arrays according to
var allArray = result.split(",");
//Loop this array, note that it starts from 1, because the first character of the received string is ,, so the first array after splitting is empty
for(var i=1;i<allArray.length;i++)
{
//Split this string into arrays according to |
var thisArray = allArray[i].split("|");
//Add entries to dListChild
document.getElementById("dListChild").options.add(new Option(thisArray[1].toString(),thisArray[0].toString()));
}
}
}
}
//Send data, please pay attention to the order and parameters. The parameters must be null or ""
xmlhttp.send(null);
}
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DropDownList onchange="Go(this)" id="dListParent" style="Z-INDEX: 101; LEFT: 248px; POSITION: absolute; TOP: 40px"
runat="server">
<asp:ListItem Value="100">Motorola</asp:ListItem>
<asp:ListItem Value="101">Nokia</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="dListChild" style="Z-INDEX: 102; LEFT: 248px; POSITION: absolute; TOP: 104px"
runat="server"></asp:DropDownList>
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 256px; POSITION: absolute; TOP: 176px" runat="server"
Text="Button"></asp:Button>
</form>
</body>
</HTML>
Backend webform1.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Data.SqlClient;
namespace drop
{
/// <summary>
/// Summary description of WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList dListParent;
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.DropDownList dListChild;
private void Page_Load(object sender, System.EventArgs e)
{
//Put user code here to initialize the page
//if(!IsPostBack)
//{
BindDrop();//If it is not submitted back, bind the list box
//}
}
protected void BindDrop()
{
//First of all, I want the parent dropdownlist to also be bound to the database, but I don’t think it is necessary later.
//if(!IsPostBack)
//{
//Bind parent dListParent
//BindParent();
//}
//Get the passed parent_id value, if it is the first request, it will be null
string str = Request.QueryString["parent_id"];
string str1 = dListParent.SelectedValue;;
Response.Write(str1);
//If str adds a string!=the original string, it means that the onchange event of dListParent has been triggered
if((str+"abc")!="abc")
{
//Bind dListChild control
BindChild(str);//Use the passed value of the parent DropDownList as a parameter
}
else
BindParent(str1);
}
protected void BindParent(string str)
{
//If it is the first request or the page is refreshed, it will be selected based on the value of dListParent.
//Convert parameters into int
int i = Convert.ToInt32(str);
dListChild.Items.Clear();
dListChild.Items.Add(new ListItem("All models","0"));
//Get the database connection string
string connStr = ConfigurationSettings.AppSettings["ConnString"].ToString();
//Initialize a conn object
SqlConnection conn = new SqlConnection(connStr);
//database statement
string commStr = string.Format("select type_value,type_text from phone_type where parent_id={0}",i);
//Create database command object
SqlCommand comm = new SqlCommand(commStr,conn);
//Open the database
conn.Open();
//Execute command
SqlDataReader dr = comm.ExecuteReader();
//Loop dr and add entries to dListParent
while(dr.Read())
{
dListChild.Items.Add(new ListItem(dr[1].ToString(),dr[0].ToString()));
//It can also be like this
//dListParent.Items.Add(new ListItem(dr["phone_text"].ToString(),dr["phone_value"].ToString()));
}
dListParent.Items[0].Selected = true;
//Adding the following means that the state of the second dListChild can be saved when the submit button is clicked to submit the form.
dListChild.SelectedValue = Request.Form["dListChild"];
dr.Close();
conn.Close();
}
protected void BindChild(string str)
{
//Content added through js to any control including dropdownlist will not be saved.
//Convert parameters into int
int i = Convert.ToInt32(str);
//Define a string to save the data returned from the database
string result = "";
//Clear the output first
Response.Clear();
string connStr = ConfigurationSettings.AppSettings["ConnString"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand comm = conn.CreateCommand();
string commStr = string.Format("select type_value,type_text from phone_type where parent_id = {0}",i);
comm.CommandText = commStr;
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while(dr.Read())
{
result += ","+dr[0].ToString() +"|" + dr[1].ToString();
//dListChild.Items.Add(new ListItem(dr[1].ToString(),dr[0].ToString()));
}
//Output the information obtained from the database to the client
Response.Write(result);
//Close Response after output is completed to avoid unnecessary output
Response.Flush();
Response.Close();
dr.Close();
conn.Close();
}
#region Web Forms Designer Generated Code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Forms designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Designer supports required methods - do not use code editor to modify
/// The content of this method.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write(Request.Form["dListChild"].ToString());
}
}
}
Data sheet:
Primary key id parent_id(int) type_value(int) type_text(varchar)
int increments the value of the parent drop-down box the value of the drop-down box the text of the drop-down box