透過 JQuery ajax call codebehind method 刷新 DropDownList 的選項為範例。
首先,這是 Server side 取回第二個下拉選單資料的方法
要注意
- [WebMethod]
- public static string UpdateDropDownListSpecies(string family)
- {
- string json = "[]";
- if (family == "Cat")
- {
- json = JsonConvert.SerializeObject(_cats);
- }
- else if (family == "Dog")
- {
- json = JsonConvert.SerializeObject(_dogs);
- }
- return json;
- }
- 要 [WebMethod],其實正規來說這種應該寫在 WebService,寫在 aspx 算偷懶。
- 需要是 static 的,所以取用的資料來源也要注意範圍。
Client side
記得
- $.ajax({
- type: "POST",
- url: "Default.aspx/UpdateDropDownListSpecies",
- data: "{'family':'" + family + "'}",
- contentType: "application/json; charset=utf-8",
- success: function (data) {
- $("#DropDownList_species").empty();
- $.each(JSON.parse(data.d), function (i, value) {
- $("#DropDownList_species").append($("<option>").text(value).attr("value", value));
- });
- },
- error: function (data) {
- }
- });
- 要有 contentType
- 取回來的 json 要先反解回物件才能用
- 取回來的內容在 property d 下
Event validation 有問題,請參考 這篇,這次實作是採用保哥提的解。
Example: Github
沒有留言:
張貼留言