使用 AjaxPro 來完成二級聯動的效果

現在在實現二級連動或是三級連動方面,都是採用ajax來完成的。網上的例子也很多。 我採用的是AjaxPro來完的。 如何配置AjaxPro我就不說了。
BigClassid 前臺頁面
<script type="text/javascript">    
function ShowCity(id)    
{    
var result = chen.getCityList(id).value;    
var ddlcity = document.getElementById("ddlCity");    
ddlcity.length=0;    
for(var i=0; i<result.Rows.length; i++)    
{    
ddlcity.options.add(new Option(result.Rows[i].SmallClass,result.Rows[i].id));    
}    
}    
</script>    
</head>    
<body>    
<form id="form1" runat="server">    
<p>    
省份:<asp:DropDownList ID="ddlPro" runat="server">    
</asp:DropDownList>    
市區:<asp:DropDownList ID="ddlCity" runat="server">    
</asp:DropDownList>    
</p>    
<div>    

</div>    
</form>    
</body>    
<script type="text/javascript">
function ShowCity(id)
{
var result = chen.getCityList(id).value;    
var ddlcity = document.getElementById("ddlCity");    
ddlcity.length=0;    
for(var i=0; i<result.Rows.length; i++)
{
ddlcity.options.add(new Option(result.Rows[i].SmallClass,result.Rows[i].id));    
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<p>
省份:<asp:DropDownList ID="ddlPro" runat="server">
</asp:DropDownList>
市區:<asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList>
</p>
<div>

</div>
</form>
</body>
後臺:
[AjaxPro.AjaxNamespace("chen")]    
public partial class ddlTwo : System.Web.UI.Page    
{    
protected void Page_Load(object sender, EventArgs e)    
{    
AjaxPro.Utility.RegisterTypeForAjax(typeof(ddlTwo));    

SqlConnection conn = new SqlConnection("server=.; uid=sa; pwd=chen123; database=C_News; ");    
conn.Open();    
SqlCommand cmd = new SqlCommand("", conn);    
string strsql = "select * from C_BigClass";    
cmd.CommandText = strsql;    
SqlDataAdapter da = new SqlDataAdapter();    
da.SelectCommand = cmd;    
DataTable dt = new DataTable();    
da.Fill(dt);    

this.ddlPro.DataSource = dt;    
this.ddlPro.DataValueField = "id";    
this.ddlPro.DataTextField = "BigClass";    
this.ddlPro.DataBind();    

this.ddlPro.Attributes["onchange"] = "ShowCity(this.options[selectedIndex].value)";    

conn.Close();    
}    

[AjaxPro.AjaxMethod]    
public DataTable getCityList(int id)    
{    
Hashtable ht = new Hashtable();    

SqlConnection conn = new SqlConnection("server=.; uid=sa; pwd=chen123; database=C_News; ");    
conn.Open();    
SqlCommand cmd = new SqlCommand("", conn);    
string strsql = "select * from C_SmallClass where BigClassid="+id+"";    
cmd.CommandText = strsql;    
SqlDataAdapter da = new SqlDataAdapter();    
da.SelectCommand = cmd;    
DataTable dt = new DataTable();    
da.Fill(dt);    

return dt;    
}    
}

  如果我們要進行三級或四級連動,其實很簡單,只要在Page_load下面this.ddlPro.Attributes["onchange"] = "ShowCity(this.options[selectedIndex].value)"; 的下面爲每個下拉框都加一個方法就行了。只不過多寫幾個public DataTable getCityList(int id)的程序。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章