淘汰赛填充上下拉的变化领域 [英] knockout populate fields on change of dropdown
问题描述
我在淘汰赛JS新的,我这个问题苦苦挣扎,需要你的指导。一切正常我是寓言获得的ProductID
,它是 ProductOffers
VIA 阿贾克斯
但是当我第二个下拉菜单
不填充本身。
<表>
<&THEAD GT;
&所述; TR>
百分位>< /第i
<第i产品与LT; /第i
<第i产品信息和LT; /第i
<第i价格与LT; /第i
<第i个股票及LT; /第i
< / TR>
< / THEAD>
<&TBODY GT;
&所述; TR>
&所述; TD>
<选择数据绑定=选项:产品,optionsText:名称,optionsValue:'ID',值:产品ID,optionsCaption: - />
< / TD>
< TD数据绑定=如果:产品ID>
<选择数据绑定=选择:ProductOffers,optionsText:名称,optionsValue:'ID',值:ProductOfferID,optionsCaption: - />
< / TD>
< TD>< / TD>
< TD>< / TD>
< / TR>
< / TBODY>
< /表><脚本类型=文/ JavaScript的> 功能产品(编号,名称){
this.ID = ID;
this.Name =名称;
}
功能要约(ID,姓名){
this.ID = ID;
this.Name =名称;
} VAR视图模型= {
产品:ko.observableArray(小于%= LoadProducts()%&1+), 产品编号:ko.observable('0'),
ProductOfferID:ko.observable('0'), ProductOffers:ko.observable()
}; viewModel.ProductID.subscribe(功能(newValue)以{
如果(typeof运算为newValue!=未定义){
//警报(选择的产品是:+为newValue);
viewModel.ProductOffers = GetProductOffers(为newValue);
//alert(viewModel.ProductOffers);
}
}); ko.extenders.numeric =功能(目标,precision){
//创建计算观察到的拦截可写写入我们观察到的
VAR的结果= ko.computed({
解读:目标,始终//返回原来的价值可观测
写:功能(newValue)以{
VAR电流=目标()
roundingMultiplier = Math.pow(10,precision)
newValueAsNum = isNaN(newValue)以? 0:parseFloat(+为newValue)
valueToWrite = Math.round(newValueAsNum * roundingMultiplier)/ roundingMultiplier; //只有当它改变了写
如果(valueToWrite!==电流){
目标(valueToWrite);
}其他{
//如果舍入值是相同的,但不同的值被写入,迫使一个通知为当前场
如果(为newValue!==电流){
target.notifySubscribers(valueToWrite);
}
}
}
}); //与当前值初始化,以确保它适当四舍五入
结果(目标()); //返回新的计算可观测
返回结果;
}; ko.applyBindings(视图模型); 功能GetProductOffers(产品ID){ 警报(读取提供产品:+产品ID) 变种缬氨酸=;
jQuery.ajax({
键入:POST,
网址:testing.aspx / GetProductOffers
数据:{产品编号:'+产品id +'},
的contentType:应用/ JSON的;字符集= UTF-8,
数据类型:JSON
异步:假的,
成功:函数(MSG){
瓦尔= msg.d;
},
错误:功能(jqXHR,除外){
如果(jqXHR.status === 0){
警报('不连接\\ n检查网络。+ jqXHR.responseText);
}否则如果(jqXHR.status == 404){
警报('。请求的页面未找到[404]'+ jqXHR.responseText);
}否则如果(jqXHR.status == 500){
警报('内部服务器错误[500]。'+ jqXHR.responseText);
}否则如果(例外==='parsererror'){
警报('请求JSON解析失败。'+ jqXHR.responseText);
}否则如果(例外==='超时'){
警报('超时错误。'+ jqXHR.responseText);
}否则如果(例外==='中止'){
警报('Ajax请求中止。'+ jqXHR.responseText);
}其他{
警报('未捕获的错误。\\ n'+ jqXHR.responseText);
}
}
});
返回瓦尔;
}
< / SCRIPT>
**编辑:**这里是什么蒂姆的输入之后hapening。
的jsfiddle: http://jsfiddle.net/neodescorpio/sPrVq/1/
编辑:
这里是Web方法,我必须改变它来产生一个有效的 JSON
acording到JSLint的。现在,第二个下拉满了,但问题是每当我改变的产品,正确的价值观是牵强,但下拉列表不显示他们这的价值观永远不会改变。
[的WebMethod]
公共静态字符串GetProductOffers(长的ProductID)
{
StringBuilder的sbScript =新的StringBuilder();
JSON字符串=[{\\ID \\:0 \\名称\\:\\对不起!没有找到数据\\}];
布尔第一= TRUE; 清单< DMS.ProductOfferDO>提供= ProductOffers.Get(产品ID); 如果(报价= NULL&放大器;!&安培; offers.Count大于0)
{
sbScript.Append([);
的foreach(在offers.OrderBy(D VAR X => d.IsCashOffer))
{
如果(第一)
{
sbScript.Append(的String.Format({{\\ID \\:{0},\\名称\\:\\{1} \\}},x.ID,x.Name));
第一= FALSE;
}
其他
{
sbScript.Append(的String.Format({{\\ID \\:{0},\\名称\\:\\{1} \\}},x.ID,x.Name));
}
}
sbScript.Append(]);
JSON = sbScript.ToString();
}
返回JSON;
}
为什么要声明 ProductOffers
为 ko.observable()
?它应该被宣布为一个可观察的数组来代替: ProductOffers:ko.observableArray([]);
另外,在你的JFiddle:
函数GetProductOffers(产品ID){
VAR瓦尔=[新发售(1,名称),新的报价(2,产品A),新的报价(4'产品B'),新的报价(5,产品C');
返回瓦尔;
}
应该是:
函数GetProductOffers(产品ID){
VAR瓦尔= [新发售(1,名称),新的报价(2,产品A),新的报价(4'产品B'),新的报价(5,产品C')];
返回瓦尔;
}
编辑:
尝试修改您的设置如下:
[的WebMethod]
公共静态字符串GetProductOffers(长的ProductID)
{
清单< DMS.ProductOfferDO>提供= ProductOffers.Get(产品ID); 返回JsonConvert.SerializeObject(报价);
}
您需要导入:使用Newtonsoft.Json;
第一疗程
和你为什么使用POST?这应该是一个GET:
函数GetProductOffers(产品ID){ $获得(testing.aspx / GetProductOffers
{产品编号:ko.toJSON(产品ID)}
)
.done(功能(数据){
viewModel.ProductOffers(JSON.parse(数据));
})
.fail(功能(数据){})
。总是(函数(){});}
EDIT2:
viewModel.ProductID.subscribe(功能(newValue)以{ viewModel.ProductOffers.removeAll(); 如果(newValue)以{
VAR productOffers = GetProductOffers(为newValue);
viewModel.ProductOffers(productOffers);
}});
让我们知道如何去这个请!
I'm new at Knockout JS and i am struggling with this issue, need your guidance. Everything works fine i am fable to get ProductID
and it's ProductOffers
VIA Ajax
but when i second dropdown
doesn't populates itself.
<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>
**EDIT : ** here is a what is hapening after tim's input.
JSFiddle : http://jsfiddle.net/neodescorpio/sPrVq/1/
EDIT :
here is the web method , i have changes it to produce a valid JSON
acording to JSLint. Now the 2nd dropdown fills up but the problem is it's values never change whenever i change products, correct values are fetched but dropdown doesn't shows them.
[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;
}
Why are you declaring ProductOffers
as ko.observable("")
? It should be declared as an observable array instead: ProductOffers: ko.observableArray([]);
Also, in your 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;
}
Should be:
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;
}
EDIT:
Try to modify your setup as follows:
[WebMethod]
public static string GetProductOffers(long ProductID)
{
List<DMS.ProductOfferDO> offers = ProductOffers.Get(ProductID);
return JsonConvert.SerializeObject(offers);
}
You need to import: using Newtonsoft.Json;
first of course.
And why did you use post? It should be a get:
function GetProductOffers(ProductID) {
$.get("testing.aspx/GetProductOffers",
{ ProductID: ko.toJSON(ProductID) }
)
.done(function (data) {
viewModel.ProductOffers(JSON.parse(data));
})
.fail(function (data) { })
.always(function () { });
}
EDIT2:
viewModel.ProductID.subscribe(function (newValue) {
viewModel.ProductOffers.removeAll();
if (newValue) {
var productOffers = GetProductOffers(newValue);
viewModel.ProductOffers(productOffers);
}
});
Let us know how this goes please!
这篇关于淘汰赛填充上下拉的变化领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!