【发布时间】:2012-11-08 06:10:38
【问题描述】:
嗨,我被这个错误消息卡住了,我找不到解决方案。
我在 Knockout JavaScript 库 v2.2.0 中收到此消息错误:
第 1053 行第 5 列未处理的异常 本地主机:端口/脚本/敲除-2.2.0.debug.js 0x800a138f - 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>
【问题讨论】:
标签: json knockout.js asp.net-mvc-4 asp.net-web-api runtime-error