嗨,我被这个错误消息困住了,我找不到解决方案。
我在 Knockout JavaScript library v2.2.0 中收到此消息错误:
localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f 中的第 1053 行第 5 列未处理的异常 - Microsoft JScript 运行时错误:“in”的操作数无效:预期对象 如果有此异常的处理程序,则程序可以安全地继续。
它在 knockout-2.2.0.debug.js 中的这行代码处停止
if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
我使用这个 WebApi:
public class ProductsController : ApiController
{
IEnumerable<Product> products = new List<Product>()
{
new Product { Id = 1, Name = "Tomato_Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts(){
return products.AsEnumerable(); }
我使用的脚本位于标题部分
@section Testscripts
{
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
}
以及页脚默认脚本部分中的 Knockout 代码
@section scripts
{
<script type="text/javascript">
var apiUrl = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
function Product(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Price = ko.observableArray(data.Price);
this.Category = ko.observable(data.Category);
}
function ProductViewModel() {
var self = this;
self.myproducts = ko.observableArray([]);
$.getJSON(apiUrl, function (allData) {
var mappedProducts = $.map(allData, function (item) { return new Product(item) });
self.myproducts(mappedProducts);
});
};
ko.applyBindings(new ProductViewModel);
}
并在正文中显示数据:
<ul data-bind="foreach: myproducts">
<li>
<input data-bind="value: Id" />
<input data-bind="value: Name" />
<input data-bind="value: Category" />
<input data-bind="value: Price" />
</li>
</ul>