我正在學習knockoutjs並遇到一些問題。我有一個返回三個Car對象列表的方法的ASP.NET MVC頁面是JSON。我將它映射到HTML視圖中的select
,我想在選擇更改時顯示所選汽車的成本。問題是,一輛汽車的名字是可見的,而價格不是('梅賽德斯 - 奔馳的成本')。它可能是什麼?提前致謝! 控制器:Knockoutjs綁定對象問題
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);
}
並查看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>
謝謝你的解釋! – IDeveloper