ajax寫級聯效果,動態從資料庫獲取資料
阿新 • • 發佈:2019-01-29
要實現的級聯資料的效果是,諮詢方式有多種,有的有子諮詢方式,有的沒有,直接上圖
圖一中選擇自選方式,例如:選擇面詢,效果如圖二,後面對應的有面詢的子諮詢方式,有的沒有子諮詢方式,如圖三,沒有子諮詢方式,後面不顯示
圖一 圖二 圖三
需要建立的
1.aspx頁面
dropdownlist控制元件繫結的資料從資料庫中獲取
/// <summary>
/// 獲取諮詢方式
/// </summary>
private void GetConsultantType()
{
IList items = new ArrayList();
ListItem title = new ListItem();
title.Text = "諮詢方式";
title.Value = "-1";
this.ddlConsultantTypeId1.Items.Add(title);
items = DAL.OzOa_Dal.ListOrderByTypeDal.GetConsultantTypeById();
for (int i = 0; i < items.Count; i++)
{
DAL.Model.RecepInfoType recpInfoType = (DAL.Model.RecepInfoType)items[i];
ListItem temp = new ListItem();
temp.Text = recpInfoType.rIType.ToString();
temp.Value = recpInfoType.rITypeID.ToString();
this.ddlConsultantTypeId1.Items.Add(temp);
}
}
對應的級聯select控制元件中的資料,通過ajax無重新整理的形式獲取,首先建立一個js檔案,和一個一般處理程式檔案。
ConPro.js
$(document).ready(function () {
$("#ddlConsultantTypeId1").change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: "../ashx/ConPro.ashx",
data: { type: "ConsultantType", id: id },
success: function (data) {
if (data == "fail") {
alert("loading failed");
}
else {
addProvinceList(data);
}
}
});
});
});
function addProvinceList(str) {
var strArray = str.split(";");
$("#selConsultantTypeId2").empty();
if (strArray.length == 1) {
for (var i = 0; i < strArray.length; i++) {
var strOptArr = strArray[i].split(",");
$("#selConsultantTypeId2").append("<option value='" + strOptArr[0] + "'></option>");
}
} else {
for (var i = 0; i < strArray.length; i++) {
var strOptArr = strArray[i].split(",");
$("#selConsultantTypeId2").append("<option value='" + strOptArr[0] + "'>" + strOptArr[1] + "</option>");
}
}
}
ConPro.ashx
using DAL.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace OzoA.ashx
{
/// <summary>
/// ConPro 的摘要說明
/// 諮詢方式實現省市級聯的效果
/// </summary>
public class ConPro : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string type = context.Request["type"];
string id = context.Request["id"];
StringBuilder listStr = new StringBuilder();
if (type == "ConsultantType")
{
IList<RecepInfoType> consultantType = DAL.OzOa_Dal.ListOrderByTypeDal.GetConsultantType2ById1(id);
if (consultantType.Count == 0)
{
context.Response.Write(listStr);
}
else
{
foreach (RecepInfoType recepInfoType in consultantType)
{
listStr.Append(recepInfoType.rITypeID + "," + recepInfoType.rIType + ";");
}
int startIn;
startIn = listStr.Length - 1;
listStr.Remove(startIn, 1);
context.Response.Write(listStr);
}
}
else
{
context.Response.Write("fail");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
寫上這些基本級聯效果搞定,最後一個說如何在後臺獲取select中的資料
string consultantType1 = this.ddlConsultantTypeId1.SelectedValue;//諮詢方式1
//string consultantType3 = this.selConsultantTypeId2.SelectedValue;//諮詢方式2
string consultantType2 = Request.Form[“selConsultantTypeId2”];