2

Hy,이 오류 메시지가 계속 표시되어 해결책을 찾을 수 없습니다.MVC4 WebApi 녹아웃 JSON 'in'에 대한 피연산자가 올바르지 않음

가 나는 녹아웃 자바 스크립트 라이브러리 V2.2.0이 메시지 오류 :

Unhandled exception at line 1053, column 5 in localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f - Microsoft JScript runtime error: Invalid operand to 'in': Object expected If there is a handler for this exception, the program may be safely continued.

그것은 녹아웃-2.2.0.debug.js

if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues)) 

I에서 코드 줄에 중단 이 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> 


} 

그리고 바닥 글 기본 스크립트 섹션

@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> 

답변

2

버그는 Product 기능입니다.

을 십진 값이고 값의 배열이 아닌 ko.observableArray에서 만들고 싶습니다. 그 결과 예외가 아닙니다.

ko.observable로 변경하고 작동합니다 :

function Product(data) {    
     this.Id = ko.observable(data.Id); 
     this.Name = ko.observable(data.Name); 
     this.Price = ko.observable(data.Price); 
     this.Category = ko.observable(data.Category); 

    } 
+0

네, 그게 문제였다. Thnx – GeorgesC

관련 문제