asp.net-mvc-4 – 使用KNOCKOUT.JS和ASP.NET MVC 4进行级联下拉

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – 使用KNOCKOUT.JS和ASP.NET MVC 4进行级联下拉前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在关注本教程:

http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html

该项目提供的工作就像一个魅力.
它可以从这里下载:
http://files.dotnetexpertguide.com/download.aspx?key=cascadingddlknockoutjs

问题是 – 我无法弄清楚如何更改视图,以便再显示一个城市选择框,其内容会根据所选的状态而变化?

为城市编写另一个模型,并在控制器中按状态ID获取城市的操作非常简单,但我不明白如何更改View和JS代码以使其有效.

那么View的代码

<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>

<script type='text/javascript'>

function CascadingDDLviewmodel() {
  this.states = ko.observableArray([]);
}

var objVM = new CascadingDDLviewmodel();
ko.applyBindings(objVM);

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

</script>

非常感谢任何帮助.

解决方法

<p>
<b>Select Country :</b> @Html.DropDownList("ddlCountry",new { onchange = "FetchStates();" })
</p>

<p data-bind="visible: states().length > 0">
<b>Select State :</b> <select id="ddlStates" data-bind="options: states,optionsCaption: 'Choose...'"></select>
</p>

<p data-bind="visible: cities().length > 0">
<b>Select City :</b> <select data-bind="options: cities,optionsText: 'CityName',optionsValue: 'CityId',optionsCaption: 'Choose...'"></select>
</p>

<script type='text/javascript'>

function CascadingDDLviewmodel() {
  this.states = ko.observableArray([]);
  this.cities = ko.observableArray([]);
}

var objVM = new CascadingDDLviewmodel();
ko.applyBindings(objVM);

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

function FetchCities() {
  var stateId = $("#ddlStates").val();
  $.getJSON("/Home/GetCities/" + stateId,function (data) {
    objVM.cities(data);
  });
}

</script>
原文链接:https://www.f2er.com/aspnet/245415.html

猜你在找的asp.Net相关文章