简体   繁体   English

Knockoutjs绑定对象问题

[英]Knockoutjs binding objects issue

I'm studying knockoutjs and having some issues. 我正在研究knockoutjs并遇到一些问题。 I have ASP.NET MVC page with a method returning list of three Car objects is JSON. 我有ASP.NET MVC页面,返回三个Car对象列表的方法是JSON。 I than map it to select in HTML view and I want to display cost of a selected car on selection change. 我将其映射到HTML视图中进行select ,我想在选择更改时显示所选汽车的成本。 The problem is that a name of a car is visible while a price is not ('A Mercedes-Benz costs .'). 问题是汽车的名称是可见的而价格不是('梅赛德斯 - 奔驰的成本'。)。 What it could be? 可能是什么? Thanks in advance! 提前致谢! Controller: 控制器:

public class Car
{
    public string Make { get; set; }
    public decimal Price { get; set; }
}
public JsonResult GetCars()
{
    List<Car> cars = new List<Car>();
    cars.Add(new Car { Make = "Mercedes-Benz", Price = 103000 });
    cars.Add(new Car { Make = "Toyota", Price = 37000 });
    cars.Add(new Car { Make = "Huyndai", Price = 17000 });
    return Json(cars, JsonRequestBehavior.AllowGet);
}

And View with Javascript code: 并使用Javascript代码查看:

<head>
    <script type="text/javascript" src="~/Scripts/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" src="~/Scripts/knockout-3.0.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            function Car(data) {
                this.Make = ko.observable(data.Make);
                this.Price = ko.observable(data.Price);
            }

            function CarsViewModel() {
                var self = this;
                //Data
                self.someOptions = ko.observableArray([]);
                self.myOption = ko.observable();

                //Operations
                self.initData = function () {
                    $.get('/Home/GetCars', function (data) {
                        var mappedCars = $.map(data, function (item) { return new Car(item) });
                        self.someOptions(mappedCars);
                    });
                }
            }

            ko.applyBindings(new CarsViewModel());
        });

    </script>
</head>
<body>
    <div>
        <button data-bind="click: initData">Load data</button>
        <h4>Preview</h4>
        <p>
            <select data-bind="options: someOptions, optionsText: 'Make', value: myOption"></select><br />
            A <span data-bind="text: myOption().Make"></span> costs <span data-bind="text: myOption().Price"></span>.
        </p>
    </div>
</body>

If you check your browser's JavaScript console you should see the following error: 如果您检查浏览器的JavaScript控制台,您应该会看到以下错误:

Uncaught TypeError: Unable to process binding "text: function (){return myOption().Make }" Message: Cannot read property 'Make' of undefined 未捕获的TypeError:无法处理绑定“text:function(){return myOption()。Make}”消息:无法读取未定义的属性'Make'

You get this error because when your page is loaded your myOption is empty so it does not have a Make and Price properties. 您收到此错误,因为当您的页面加载时, myOption为空,因此它没有MakePrice属性。 So KO cannot execute the binding data-bind="text: myOption().Make" and it stops with the processing of the further bindings. 所以KO无法执行绑定data-bind="text: myOption().Make"并且它会在处理进一步绑定时停止。

After calling initData now you have something in myOption but still all the bindings after the data-bind="text: myOption().Make" won't work anymore. 现在调用initData之后,你在myOption有了一些东西,但仍然是data-bind="text: myOption().Make"之后的所有绑定data-bind="text: myOption().Make"将不再起作用。

To solve this there are multiple ways like: 要解决这个问题,有多种方法可以:

  • using a default value in myOption 使用myOption中的默认值
  • check for null in your bindings with data-bind="text: myOption() && myOption().Make" 使用data-bind="text: myOption() && myOption().Make"检查绑定中的null data-bind="text: myOption() && myOption().Make"
  • or use the with binding 或使用with binding

Here is an example for the with binding: 以下是with绑定的示例:

<!-- ko with: myOption -->
   A <span data-bind="text: Make"></span> 
   costs <span data-bind="text: Price"></span>.
<!-- /ko -->

Demo JSFiddle . 演示JSFiddle

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

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