简体   繁体   中英

Get error in Knockout.js and MVC 3

this is my sample but not work and get this error in chrome Uncaught Error: Unable to parse binding attribute. Message: ReferenceError: ProductName is not defined; Attribute value: text: ProductName

Action Code:

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

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

please Help, thanks

Please check attributes/properties in _db.Products . They have not found ProductName may be it is missing. If you are using EF then refresh your EntityFramework model again. Or you can also check whether ProductName is empty or null by using alert like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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