用Knockoutjs與Asp.net MVC實現級聯下拉式清單

來源:互聯網
上載者:User

    Knockout Js 另一個javascript庫。 開源, 純Javascript,小,無依賴,支援眾多瀏覽器。在Asp.net MVC中我們來實現一個簡單的級聯下拉式清單。 先看我們定義的Controller與Model:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Country = new SelectList(Country.GetCountryList(), "Code", "Name");
            return View();
        }
 
        public ActionResult GetStates(string id = "")
        {
            var stateList = State.GetStates()
                .Where(s => s.CountryCode.ToLower() == id.ToLower());
 
            return this.Json(stateList, JsonRequestBehavior.AllowGet);
        }
    }
 
    public class Country
    {
        public string Code { get; set; }
        public string Name { get; set; }
 
        public static List<Country> GetCountryList()
        {
            return new List<Country>
            {
                new Country { Code = "IN", Name = "India" },
                new Country { Code = "US", Name = "United State" },
                new Country { Code = "UK", Name = "United Kingdom" }
            };
        }
    }
 
    public class State
    {
        public string CountryCode { get; set; }
        public int StateId { get; set; }
        public string StateName { get; set; }
 
        public static List<State> GetStates()
        {
            int stateId = 0;
            return new List<State>
            {
                new State { CountryCode = "CN", StateId = stateId++, StateName = "ShangHai" },
                new State { CountryCode = "CN", StateId = stateId++, StateName = "BeiJing" },
                new State { CountryCode = "CN", StateId = stateId++, StateName = "HongKong" },
                new State { CountryCode = "US", StateId = stateId++, StateName = "New York" },
                new State { CountryCode = "US", StateId = stateId++, StateName = "California" },
                new State { CountryCode = "US", StateId = stateId++, StateName = "Washington" },
                new State { CountryCode = "UK", StateId = stateId++, StateName = "London" },
                new State { CountryCode = "UK", StateId = stateId++, StateName = "Scotland" },
                new State { CountryCode = "UK", StateId = stateId++, StateName = "Britian" }
            };
        }
    }


注意這裡是為了示範,在MODEL填充的資料。GetStates用於Ajax請求的Action。在前端的cshtml中,類似這樣的片段:

<p>
    <b>Select Country :</b> @Html.DropDownList("ddlCountry", ViewBag.Country as SelectList, "Select...", new { onchange = "FetchStates();" })
</p>
<p data-bind="visible: states().length > 0">
    <b>Select State :</b>
    <select data-bind="options: states, optionsText: 'StateName', optionsValue: 'StateId', optionsCaption: 'Choose...'">
    </select>
</p>


上面使用visible的API,從這裡可以看出用於控制是否顯示。參考官方的Visible Binding 的 API文檔。 接著是基於select標籤options binding。 在View中Javascript定義我們的ViewModel :

function CascadingDDLViewModel() {
    this.states = ko.observableArray([]);
}
 
var objVM = new CascadingDDLViewModel();
ko.applyBindings(objVM);

 

我們看到上面的代碼中,我們建立ko.observableArray類型states屬性的ViewModel.knockoutjs中的Observable類型自動通知當它的對象被更新。

這裡又藉助的data-bind特性,之前文章中有提過它,用knockoutjs的Viewmodel來實現綁定DOM元素行為。無論ViewModel被更新,同時DOM元素也會被自動更新.

function FetchStates() {
    var countryCode = $("#ddlCountry").val();
    $.getJSON("/Home/GetStates/" + countryCode, null, function (data) {
        objVM.states(data);
    });
}

當下拉式清單改變時,我們使用jQuery.getJSON方法去獲得資料。在請求成功後更新ViewModel,而不需要手動用Javascript做字串操作來實現一個DropDownList.

您可能感興趣的文章:

Jquery實現無重新整理DropDownList聯動

Html 5中自訂data-*特性

 


作者:Petter Liu

出處:http://www.cnblogs.com/wintersun/

本文著作權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。

該文章也同時發布在我的獨立部落格中-Petter Liu Blog。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.