【问题标题】:knockout populate fields on change of dropdown剔除在下拉列表更改时填充字段
【发布时间】:2014-06-28 10:01:48
【问题描述】:

我是 Knockout JS 的新手,我正在努力解决这个问题,需要您的指导。一切正常,我很可能得到ProductID,它是ProductOffers VIA 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>

**EDIT : ** 这是 tim 输入后正在发生的事情。

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

【问题讨论】:

  • 您的示例代码中没有任何内容可以实际获取任何数据或执行任何操作来填充第一个列表选项中的第二个列表,因此我认为您要么需要包含更多代码,要么缺少一个大逻辑块。
  • @TimHobbs 感谢您的即时回复,我没有遗漏任何东西,因为我说除了问题之外它工作正常。所有我试图完成他的第二个下拉列表的事情都在第一个更改时填充。并获得一些详细信息,例如价格和库存。并显示在表格上。
  • 我的错误 - 我想我的大脑放屁了,没有向下滚动查看其余部分。 :)
  • 它有时会发生兄弟:D
  • 用 JSFiddle 更新

标签: javascript jquery asp.net knockout.js


【解决方案1】:

为什么将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;

你为什么使用post?应该是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);
    }

});

请告诉我们这是怎么回事!

【讨论】:

  • 当我像小提琴一样固定值时它工作正常,但当我使用 ajax Web 服务时它不起作用,我使用 JSON.parse 但它给出错误 SyntaxError: Unexpected token e
  • 这与您的 JSON 结果无效有关。你能验证它在这里的样子吗? jsonlint.com
  • 顺便说一句,如果您的 web 服务返回一个字符串,则使用它。你的方法返回什么?
  • 返回,JSLint 说它无效。 [new Offer(6,'1 free unit') ,new Offer(7,'1 free unit') ,new Offer(5,'100 per Unit') ]
  • 这甚至不是 JSON;然后你返回一个列表 - 你不能使用 JSON.parse :) 奇怪的是,我在小提琴中硬编码了你的返回值并且它正在工作:jsfiddle.net/sPrVq/3 看起来你的网络服务有问题,可以你检查控制台是否有任何错误?
【解决方案2】:

&lt;td data-bind="with: ProductID"&gt; 不正确 - 只有当您有 ProductID 嵌套对象时才需要这样做。你没有,所以它是不需要的。只需将第二个列表绑定到 ProductOffers 而不是 $data.ProductOffers

如果您想要实现的是在有优惠之前显示第二个列表,那么只需将&lt;td data-bind="with: ProductID"&gt; 更改为&lt;td data-bind="if: ProductOffers"&gt;,这应该会按预期工作。

编辑:
我不能肯定地说,因为我不知道返回的确切内容,但我猜ProductOffers 有问题。 ajax 调用返回结果,这就是您将ProductOffers 设置为的结果,但是每个ProductOffer 的结构是否与您为选择列表绑定设置的结构相同?您有 NameID 作为绑定值,这些属性是您从 ajax 调用 (GetProductOffers) 返回的项目的属性吗?

编辑 2
好的,我从您与 Diana 的聊天中看到,您的 Web 方法返回类似“[new Offer(..)...]”的内容。我的猜测是您将该方法编码为仅返回字符串或其他内容,对吗?您需要实际创建一个List&lt;Offer&gt;,然后使用JavascriptSerializer 或JSON.net 之类的东西对其进行序列化。您需要从 web 方法返回 JSON。如果您显示 Web 方法代码会很有帮助,然后我们可以帮助您找出问题所在。

编辑 3
我肯定会建议不要“手动”创建 JSON - 使用内置的 JavascriptSerializer,或者更好的是,使用 JSON.net。虽然它不是必须的,但它更干净、更简单。另外,可以这么说,为什么要重新发明轮子?检查Diana's answer out - 她已经准确地概述了您需要做什么才能使其正常工作。祝你好运! :)

【讨论】:

  • 更改了一些代码并发生了一些事情,但现在有一个很长的第二个列表没有显示任何内容
  • 现在显示了一百个类似&lt;option value=""&gt;&lt;/option&gt;的空选项,我不知道现在发生了什么
  • @Diana Nassar 我已将 ProductOffer 更改为标准 JSON,现在它工作正常,但现在当我更改第一个下拉列表的值时,第二个下拉列表不会自行更新。但是 ajax 请求正在获取更新的值,我可以在警报中看到它们。
猜你喜欢
  • 1970-01-01
  • 2013-07-03
  • 2017-01-14
  • 1970-01-01
  • 2012-02-11
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
相关资源
最近更新 更多