2015-06-22 38 views
3

返回的查詢的結果,這是我在得到的產品ID,並使用JSON返回supllier控制器方法:不能查看我使用JSON

public ActionResult GetProductData(int ProductId) 
      { 
       var data = from m in db.Products 
         join sa in db.SupPro on m.ProductID equals sa.ProductID 
         join f in db.Supplier on sa.CompanyID equals f.CompanyID 
         where m.ProductID == ProductId 
         select new { CompanyName = f.NameS, AdressCompany = f.Address, PhoneCompany = f.Phone }; 
       return Json(new { foo = data.ToList(), ball = "dragon", elementId = ProductId }, JsonRequestBehavior.AllowGet); 
      } 

在屏幕上的輸出是:數據水庫:[對象的對象]龍4

這些都是我的模型類:

客戶模式:

public class Customer 

{ 
    [Key] 
    public int CustomerID { get; set; } 
    public String NameS { get; set; } 
    public String NameP { get; set; } 
    public String Name { get; set; } 
    public String Phone { get; set; } 
    public String Address { get; set; } 
    public String Email { get; set; } 

    public virtual ICollection<SupPro> SupPro { get; set; } 
} 

的供應者類:

public class Supplier 
     { 
      [Key] 
      public int CompanyID { get; set; } 
      public String NameS { get; set; } 
      public String Address { get; set; } 
      public String Phone { get; set; } 

      public virtual ICollection<SupPro> SupPro { get; set; } 
     } 

產品類:

public class Products 
    { 
     [Key] 
     public int ProductID { get; set; } 
     public String NameP { get; set; } 
     public decimal Price { get; set; } 
     public int Quantity { get; set; } 

     public virtual ICollection<SupPro> SupPro { get; set; } 
    } 

和supPro類:

public class SupPro 
    { 
     [Key] 
     public int SupProID { get; set; } 
     public int CustomerID { get; set; } 
     public int ProductID { get; set; } 
     public int CompanyID { get; set; } 
     public DateTime SupplyDate { get; set; } 

     public virtual Products Product { get; set; } 
     public virtual Supplier Supplier { get; set; } 
     public virtual Customer Customer { get; set; } 
    } 

有人可以告訴我什麼是我的問題,所以我將能夠根據需要查看查詢結果。

謝謝。

+0

這可以幫助你的http:// www.mkyong。com/javascript/how-to-access-json-object-in-javascript/ –

+2

向你展示客戶端代碼! –

+0

您無法直接將json數據「打印」到瀏覽器。你需要迭代json對象並使用單獨的屬性。否則,您需要使用某種綁定庫,如'knockout.js'來處理客戶端與您的html的json綁定。 – ramiramilu

回答

0

您的JSON將在一個jQuery successdone電話可訪問如下:

foo是一個集合,這樣它會通過索引或一個循環,那麼屬性名稱進行訪問。

以獲得第一個CompanyName屬性爲例。

data.foo[0].CompanyName 

更常見的是你可以使用一個循環來輸出這些與jQuery你可以使用$.each,並將其附加到的元素。

定義將通過可訪問的其它元素:

更新

success: function (data) { 
          var x = data; 

          $.each(data.foo, function (i, item) { 
           $nextElm.append(item.CompanyName + '<br/>'); 
          }); 

         } 

追加顯然更改爲您所需的輸出。

0

我不確定這是否會有所幫助,但是如果您有一個包含JSON類或數組的JavaScript變量,並且您使用的是AngularJS,那麼以可讀形式顯示值非常簡單:

<pre> {{ myArrayOfObjects | json }} </pre> 

我使用這個技巧很多,特別是在編寫AngularJS代碼時,以及測試我的控件是否綁定到JSON對象中的正確字段。

enter image description here

但是,是的,你說得對,沒有AngularJS,試圖顯示此變量的內容將只返回一個毫無意義的:

[object Object]