我正在研究 knockoutjs 并遇到了一些问题。我有一个 ASP.NET MVC 页面,其方法返回三个 Car 对象的列表是 JSON。我将其映射到select
HTML 视图中,并且我想在选择更改时显示所选汽车的成本。问题是汽车的名称是可见的,而价格是不可见的('A Mercedes-Benz costs.')。它可能是什么?提前致谢!控制器:
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>