javascript - knockout 在下拉菜单更改时填充字段

标签 javascript jquery asp.net knockout.js

我是 Knockout JS 的新手,我正在努力解决这个问题,需要你的指导。一切正常,我可以通过 Ajax 获取 ProductID 并且它是 ProductOffers,但是当我第二次 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>

**编辑:** 这是蒂姆输入后发生的情况。 my problem

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;

你为什么使用post?它应该是一个获取:

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

});

请告诉我们事情进展如何!

关于javascript - knockout 在下拉菜单更改时填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23585353/

相关文章:

javascript - 获取一列的值并将其传递给另一列

sql - 在新的数据库服务器上创建新的非对称 key 会导致旧数据失效吗?

javascript - 如何使用 native javascript 将数据附加到列表中的数组中

javascript - jQuery:编辑标签只能工作一次

javascript - Jquery nextUntil 和行单元格

javascript - 我正在制作一个代码编辑器应用程序,可让您执行 HTML/CSS/JS 代码,但 JavaScript 仅执行一次

javascript - jquery if else比较查询问题

c# - ASP NET MVC RAZOR 上传多个图像文件列表

asp.net - Razor View 中当前上下文中不存在资源

javascript - 超出范围的变量不起作用