DIV CSS 佈局教程網

ASP.NET MVC3 + jQuery 實作省市下拉列表聯動
編輯:JQuery特效代碼     

「選了中國,右邊就列出各省」這種下拉列表聯動,傳統 Web Forms 靠 AutoPostBack 就能做,但每次變動都要整頁回傳,體驗很差。改用 MVC 搭配 jQuery 的 getJSON,可以做到不換頁即時更新,程式碼也更清楚。

一、實體定義

public class DP_Provice
{
    public int proviceID { get; set; }
    public string ProviceName { get; set; }
    public int ProviceNode { get; set; }
    public virtual List<DP_City> citySource { get; set; }
}

public class DP_City
{
    public int CityNode { get; set; }
    public string CityName { get; set; }
    public string ProviceNode { get; set; }
}

二、準備資料來源

為了示範方便,這裡用靜態類別產生一組寫死的測試資料;實務上換成資料庫查詢即可。

public static class DPDataSource
{
    public static List<DP_Provice> InitalData()
    {
        return new List<DP_Provice>
        {
            new DP_Provice { ProviceNode = 1, ProviceName = "北京", citySource = new List<DP_City> {
                new DP_City { CityNode = 11, CityName = "北京海澱" },
                new DP_City { CityNode = 12, CityName = "北京西城" }
            }},
            new DP_Provice { ProviceNode = 2, ProviceName = "山東", citySource = new List<DP_City> {
                new DP_City { CityNode = 21, CityName = "濟南" },
                new DP_City { CityNode = 22, CityName = "德州" }
            }},
            new DP_Provice { ProviceNode = 3, ProviceName = "河北", citySource = new List<DP_City> {
                new DP_City { CityNode = 31, CityName = "石家莊" },
                new DP_City { CityNode = 32, CityName = "衡水" }
            }}
        };
    }
}

三、Controller:以 JsonResult 回應

public ActionResult Index()
{
    return View("DPShow");
}

List<DP_Provice> source = DPDataSource.InitalData();

public JsonResult GetProvinceSource()
{
    if (source == null || source.Count == 0)
    {
        source = DPDataSource.InitalData();
    }
    return Json(source, JsonRequestBehavior.AllowGet);
}

public JsonResult GetCitySource(string proviceName)
{
    source = DPDataSource.InitalData();
    var citySource = source
        .Where(a => a.ProviceNode.ToString().Contains(proviceName))
        .First()
        .citySource;
    return Json(citySource, JsonRequestBehavior.AllowGet);
}

JsonRequestBehavior.AllowGet 是必要的一項:MVC 預設禁止以 GET 回傳 JSON(避免 JSON 劫持風險),若前端用 getJSON 就必須明確允許。若為敏感資料,更妥的做法是改用 POST 並搭配 [HttpPost]。

四、Razor 視圖:綁定與串接

<script type="text/javascript">
$(function () {
    GetPlant();   // 初始化省份

    $("#ddlProvince").change(function () {
        GetCity();  // 省份變動時更新城市
    });
});

function GetPlant() {
    $("#ddlProvince").empty();
    var url = "/Dropdown/GetProvinceSource/";
    $.getJSON(url, function (data) {
        $.each(data, function (i, item) {
            $("<option></option>")
                .val(item["ProviceNode"])
                .text(item["ProviceName"])
                .appendTo($("#ddlProvince"));
        });
        GetCity();   // 省份填好後,順帶填一次城市
    });
}

function GetCity() {
    $("#ddlCity").empty();
    var temp = $("#ddlProvince").val();
    var url = "@Url.Action("GetCitySource", "Dropdown")";
    $.getJSON(url, { "proviceName": temp }, function (data) {
        $.each(data, function (i, item) {
            $("<option></option>")
                .val(item["CityNode"])
                .text(item["CityName"])
                .appendTo($("#ddlCity"));
        });
    });
}
</script>

<h2>下拉列表聯動</h2>
<table>
<tr>
    <td><select id="ddlProvince"></select></td>
    <td><select id="ddlCity"></select></td>
</tr>
</table>

為何建議用 Url.Action 而非寫死路徑

直接把 "/Dropdown/GetProvinceSource/" 寫在 JS 裡,在部署到虛擬目錄或變更路由設定時就會失效。改用 Razor 的 @Url.Action("Action", "Controller") 由伺服器端產生,能自動帶上正確的應用程式基底路徑, also 讓路由規則集中管理。

另外注意 $("<option></option>") 這種建立元素的方式:文字內容務必用 .text() 而非 .html() 設定,否則資料中若含 < 等字元會造成 XSS 風險。

若你對上述做法有不同的實踐或更好的方案(例如改用 $.ajax 明確指定 dataType、或在後端直接回傳已組好的 HTML 片段),歡迎提出討論。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved