0

这是我的示例,但不起作用并在 chrome 中出现此错误 Uncaught Error: Unable to parse binding attribute。消息:ReferenceError:ProductName 未定义;属性值:文本:ProductName

操作代码:

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

网页:

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

请帮忙,谢谢

4

1 回答 1

0

请检查_db.Products. 他们没有发现ProductName可能是它丢失了。如果您使用的是 EF,请再次刷新您的 EntityFramework 模型。或者,您也可以ProductName使用以下警报检查是否为空或 null:

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);
    }
于 2013-04-04T08:45:16.613 回答