AjaxPro 是早期 ASP.NET AJAX 庫,通過屬性標記後端方法,自動生成 JavaScript 代理類,實現客戶端直接呼叫伺服器端方法。本文示範省市二級聯動經典場景。
<asp:DropDownList ID="ddlStateList" runat="server"
DataTextField="StateName" DataValueField="StateId"
onchange="ShowCity(this.value)"></asp:DropDownList>
<asp:DropDownList ID="ddlCityList" runat="server"></asp:DropDownList>
<script type="text/javascript">
function ShowCity(stateId) {
// 呼叫後端代理方法 Test.GetCityList
var cities = Test.GetCityList(parseInt(stateId)).value;
var ddl = document.getElementById("<%= ddlCityList.ClientID %>");
ddl.length = 0; // 清空現有選項
if (cities) {
for (var i = 0; i < cities.length; i++) {
// 直接訪問後端返回 List<City> 的屬性
ddl.options.add(new Option(cities[i].CityName, cities[i].CityId));
}
}
}
</script>
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var states = new List<State> {
new State(0, "請選擇"), new State(1, "北京"), new State(2, "天津"),
new State(3, "上海"), new State(4, "湖北"), new State(5, "湖南"), new State(6, "山西")
};
ddlStateList.DataSource = states;
ddlStateList.DataBind();
}
// 註冊當前類型供 AjaxPro 生成代理
AjaxPro.Utility.RegisterTypeForAjax(typeof(Test));
}
[AjaxPro.AjaxMethod]
public List<City> GetCityList(int stateId)
{
var allCities = new List<City> {
new City(11, "海澱區", 1), new City(12, "朝陽區", 1),
new City(13, "大港區", 2), new City(14, "南開區", 2),
new City(15, "普陀區", 3), new City(16, "黃浦區", 3),
new City(17, "黃岡市", 4), new City(18, "荊州市", 4),
new City(19, "長沙市", 5), new City(20, "岳陽市", 5),
new City(21, "太原市", 6), new City(22, "大同市", 6)
};
return allCities.Where(c => c.StateId == stateId).ToList();
}
}
public class State { public int StateId { get; set; } public string StateName { get; set; }
public State(int id, string name) { StateId = id; StateName = name; } }
public class City { public int CityId { get; set; } public string CityName { get; set; } public int StateId { get; set; }
public City(int id, string name, int stateId) { CityId = id; CityName = name; StateId = stateId; } }
cities[i].CityName),無需手工序列化/反序列化 JSON。RegisterTypeForAjax 會動態生成 /ajaxpro/Test.ashx 處理請求路由。.error 回調捕獲伺服器異常。新專案建議採用:
AjaxPro 雖已停止維護,但其「屬性標記 + 自動代理」的設計思想深度影響了後續 ASP.NET AJAX 生態,理解其原理有助於掌握現代框架的底層機制。