1.在用戶端編寫 “OnSelectedIndexChanged” 事件
由於在用戶端不識別 OnSelectedIndexChanged 事件,但是我們可以寫其 onchange 事件,然後為
DropDownList 動態添加屬性(onchange)。
<asp:DropDownList ID="SelectProvince" runat="server" AutoPostBack="True"></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
2.Default.aspx.cs
Code
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
6.web.config
<connectionStrings>
<add name="DbConn" connectionString="Server=.; database=ProvinceCity; uid=sa; pwd=qingtian"/>
</connectionStrings>
這裡要用到資料庫的串連.如果要用上面的例子,請下載相關資料庫。
資料庫檔案下載