我是Knockout JS的新手,我正为这个问题而苦苦挣扎,需要您的指导。一切正常,我可以得到ProductID
,它是ProductOffers
威盛Ajax
,但是当我第二个dropdown
不会自动填充。
<table>
<thead>
<tr>
<th></th>
<th>Product</th>
<th>Product Offers</th>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select data-bind="options: Products, optionsText: 'Name',optionsValue: 'ID', value: ProductID, optionsCaption: '-'" />
</td>
<td data-bind="if: ProductID">
<select data-bind="options: ProductOffers, optionsText: 'Name',optionsValue: 'ID', value: ProductOfferID, optionsCaption: '-'" />
</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function Product(id, name) {
this.ID = id;
this.Name = name;
}
function Offer(id, name) {
this.ID = id;
this.Name = name;
}
var viewModel = {
Products: ko.observableArray(<%= LoadProducts() %>),
ProductID: ko.observable('0'),
ProductOfferID: ko.observable('0'),
ProductOffers: ko.observable("")
};
viewModel.ProductID.subscribe(function (newValue) {
if (typeof newValue != "undefined") {
//alert("Selected product is : " + newValue);
viewModel.ProductOffers = GetProductOffers(newValue);
//alert(viewModel.ProductOffers);
}
});
ko.extenders.numeric = function (target, precision) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
ko.applyBindings(viewModel);
function GetProductOffers(ProductID) {
alert("Fetching offers for Product : " + ProductID)
var Val = "";
jQuery.ajax({
type: "POST",
url: "testing.aspx/GetProductOffers",
data: "{ProductID: '" + ProductID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
Val = msg.d;
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.' + jqXHR.responseText);
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]' + jqXHR.responseText);
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].' + jqXHR.responseText);
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.' + jqXHR.responseText);
} else if (exception === 'timeout') {
alert('Time out error.' + jqXHR.responseText);
} else if (exception === 'abort') {
alert('Ajax request aborted.' + jqXHR.responseText);
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
return Val;
}
</script>
**编辑:**这是蒂姆输入后发生的事情。
JSFiddle:http://jsfiddle.net/neodescorpio/sPrVq/1/
编辑:
这是web方法,我对其进行了更改,以根据JSLint生成有效的
JSON
。现在,第二个下拉列表已满,但问题是,每当我更改产品时,值就永远不会改变,会获取正确的值,但下拉列表中不会显示它们。 [WebMethod]
public static string GetProductOffers(long ProductID)
{
StringBuilder sbScript = new StringBuilder();
string json = "[{\"ID\": 0,\"Name\": \"Sorry ! No data found\"}]";
bool first = true;
List<DMS.ProductOfferDO> offers = ProductOffers.Get(ProductID);
if (offers != null && offers.Count > 0)
{
sbScript.Append("[");
foreach (var x in offers.OrderBy(d => d.IsCashOffer))
{
if (first)
{
sbScript.Append(string.Format("{{\"ID\": {0},\"Name\": \"{1}\"}}", x.ID, x.Name));
first = false;
}
else
{
sbScript.Append(string.Format(",{{\"ID\": {0},\"Name\": \"{1}\"}}", x.ID, x.Name));
}
}
sbScript.Append("]");
json = sbScript.ToString();
}
return json;
}
最佳答案
为什么将ProductOffers
声明为ko.observable("")
?应该将其声明为可观察数组:ProductOffers: ko.observableArray([]);
另外,在您的JFiddle中:
function GetProductOffers(ProductID) {
var Val = "[new Offer(1,'Name'),new Offer(2,'Product A'),new Offer(4,'Product B'),new Offer(5,'Product C')]";
return Val;
}
应该:
function GetProductOffers(ProductID) {
var Val = [new Offer(1,'Name'),new Offer(2,'Product A'),new Offer(4,'Product B'),new Offer(5,'Product C')];
return Val;
}
http://jsfiddle.net/sPrVq/2/
编辑:
尝试如下修改您的设置:
[WebMethod]
public static string GetProductOffers(long ProductID)
{
List<DMS.ProductOfferDO> offers = ProductOffers.Get(ProductID);
return JsonConvert.SerializeObject(offers);
}
您首先需要导入:
using Newtonsoft.Json;
。为什么要使用邮政?应该得到:
function GetProductOffers(ProductID) {
$.get("testing.aspx/GetProductOffers",
{ ProductID: ko.toJSON(ProductID) }
)
.done(function (data) {
viewModel.ProductOffers(JSON.parse(data));
})
.fail(function (data) { })
.always(function () { });
}
编辑2:
viewModel.ProductID.subscribe(function (newValue) {
viewModel.ProductOffers.removeAll();
if (newValue) {
var productOffers = GetProductOffers(newValue);
viewModel.ProductOffers(productOffers);
}
});
让我们知道这是怎么回事!