繁体   English   中英

在Knockout.js和MVC 3中出错

[英]Get error in Knockout.js and MVC 3

这是我的示例,但无法正常工作,并且在chrome中出现此错误未捕获的错误:无法解析绑定属性。 消息:ReferenceError:未定义产品名称; 属性值:文本:ProductName

动作代码:

    public ActionResult GetProducts()
    {
        var product = _db.Products;
        return Json(product, JsonRequestBehavior.AllowGet);
    }

HTML:

    <table id="timesheets" class="table table-striped table-hover table-condensed">   
        <thead>
            <tr>
                <th>ProductName</th>
                <th>CategoryID</th>
                <th>UnitPrice</th>
                <th>Discontinued</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: viewModel.Products">
            <tr>
                <td data-bind="text: ProductName"></td>
                <td data-bind="text: CategoryID"></td>
                <td data-bind="text: UnitPrice"></td>
                <td data-bind="text: year"></td>
            </tr>
        </tbody>
    </table>

JavaScript代码:

<script type="text/javascript">

    $(function () {
        viewModel.loadProducts();
        ko.applyBindings(viewModel);
    });

    function Product(data) {
        this.ProductID = ko.observable(data.ProductID);
        this.ProductName = ko.observable(data.ProductName);
        this.CategoryID = ko.observable(data.CategoryID);
        this.UnitPrice = ko.observable(data.UnitPrice);
        this.Discontinued = ko.observable(data.Discontinued);
    }

    var viewModel = {

        Products: ko.observableArray([]),

        loadProducts: function () {

            var self = this;
            $.getJSON(
                '/Home/GetProducts',
                function (products) {
                    self.Products.removeAll();

                    $.each(products, function (index, item) {
                        self.Products.push(new Product(item));
                    });
                }
            );
        }
    };

</script>

请帮助,谢谢

请检查_db.Products属性/属性。 他们尚未找到可能缺少的ProductName 如果您使用的是EF,请再次刷新EntityFramework模型。 或者,您也可以使用以下警报来检查ProductName是空还是空:

function Product(data) {
        alert(data.ProductName);
        this.ProductID = ko.observable(data.ProductID);
        this.ProductName = ko.observable(data.ProductName);
        this.CategoryID = ko.observable(data.CategoryID);
        this.UnitPrice = ko.observable(data.UnitPrice);
        this.Discontinued = ko.observable(data.Discontinued);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM