1.在客户端编写 “OnSelectedIndexChanged” 事件
由于在客户端不识别 OnSelectedIndexChanged 事件,但是我们可以写其 onchange 事件,然后为
DropDownList 动态添加属性(onchange)。
<asp:DropDownList ID="SelectProvince" runat="server" AutoPostBack="True" onchange="SelectionChanged"></asp:DropDownList>
this.SelectProvince.Attributes.Add("onchange", "return SelectionChanged();");
2.在客户端动态绑定 DropDownList 的值
var option = document.createElement("option");
option.text = message[1];
option.value = message[0];
selectCity.options.add(option);
3.通过 javascript 获取 DropDownList 的值
var dropDownList = document.getElementById("SelectProvince");
var provinceId = dropDownList.options[dropDownList.selectedIndex].value;
3.通过 Ajax 实现省市联动。
我做了一个 Test ,不多说,看代码:
1.Default.aspx
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Home Page</title>
<script src="xmlHttp.js" type="text/javascript" language="javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="SelectProvince" runat="server" AutoPostBack="True" onchange="SelectionChanged">
</asp:DropDownList>
<br /><br />
<asp:DropDownList ID="SelectCity" runat="server">
</asp:DropDownList>
<br /><br />
<asp:Label ID="ProvinceName" runat="server" Text="[ProvinceName]"></asp:Label>
</div>
</form>
</body>
</html>
2.Default.aspx.cs
Code
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connectionString = ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
ProvinceBind();
this.SelectProvince.Attributes.Add("onchange", "return SelectionChanged();");
}
}
private void ProvinceBind()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
string sqlString = "select CityId,CityName from City where RootId=0";
cmd.CommandText = sqlString;
using (SqlDataReader dr = cmd.ExecuteReader())
{
this.SelectProvince.Items.Clear();
this.SelectProvince.DataSource = dr;
this.SelectProvince.DataTextField = "CityName";
this.SelectProvince.DataValueField = "CityId";
this.SelectProvince.DataBind();
}
}
}
this.SelectProvince.Items.Insert(0, "-请选择-");
this.SelectCity.Items.Clear();
this.SelectCity.Items.Insert(0, "-请选择-");
}
}
3.Hello.aspx (XMLHttpRequest 的url)
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Hello.aspx.cs" Inherits="Hello" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
4.Hello.aspx.cs
Code
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 System.Data.SqlClient;
public partial class Hello : System.Web.UI.Page
{
string connectionString = ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
string rootID = null;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["rootId"] != null)
{
rootID = Request.QueryString["rootId"].ToString();
SendCityInfo();
}
}
public void SendCityInfo()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(rootID);
cmd.CommandText = "select CityId,CityName from City where rootId = @id";
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
string id = dr["CityId"].ToString();
string name = dr["CityName"].ToString();
Response.Write(id + " " + name);
Response.Write("$");
}
}
}
}
}
}
5.xmlHttp.js
Code
var xmlHttp;
function CreateXMLHttpRequest()
{
if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e)
{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
}
if(!xmlHttp)
{
window.alert("Browser is not support the XMLHttpRequest!");
}
}
function SelectionChanged()
{
//window.alert("OK");
// Incorrect
//var index = $get('<%=SelectProvince.ClientID %>').selectedIndex;
//var provinceName = $get('<%=SelectProvince.ClientID %>').options[index].value;
// Correct
var dropDownList = document.getElementById("SelectProvince");
var provinceId = dropDownList.options[dropDownList.selectedIndex].value;
//var provinceName = dropDownList.options[dropDownList.selectedIndex].text;
//document.getElementById("ProvinceName").innerHTML = provinceId + " " + provinceName;
CreateXMLHttpRequest();
xmlHttp.onreadystatechange = ChangedCallBack;
var url = "Hello.aspx?rootId=" + provinceId;
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
function ChangedCallBack()
{
var selectCity = document.getElementById("SelectCity");
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
if(selectCity.options.length > 1)
{
//alert("OK");
for(var i=selectCity.options.length-1; i>0; i--)
{
//alert(i);
selectCity.remove(i);
}
}
var msg = xmlHttp.responseText;
document.getElementById("ProvinceName").innerHTML = msg;
var provincelist = msg.split('$');
for(var i=0; i<provincelist.length; i++)
{
var message = provincelist[i].split(' ');
var option = document.createElement("option");
option.text = message[1];
option.value = message[0];
selectCity.options.add(option);
}
}
}
} 6.web.config
<connectionStrings>
<add name="DbConn" connectionString="Server=.; database=ProvinceCity; uid=sa; pwd=qingtian"/>
</connectionStrings>
这里要用到数据库的连接.如果要用上面的例子,请下载相关数据库。
数据库文件下载
Tag标签: Ajax