2013-01-15 119 views
0

JSON對象我有一個看起來像這樣一個視圖模型:創建一個從C#類

public class CategoriesJsonViewModel 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public List<Description> UsedDescriptions { get; set; } 
    public List<Description> UnusedDescriptions { get; set; } 
} 

我在我的控制器創建CategoriesJsonViewModel的名單,並試圖將其發送到JSON格式的客戶端瀏覽器。我使用JSON()方法來做到這一點:

List<CategoriesJsonViewModel> categoriesVM = new List<CategoriesJsonViewModel>(); 
List<Category> categories = repo.GetAllCategories(); 
foreach(var i in categories) 
{ 
      CategoriesJsonViewModel categoryVM = new CategoriesJsonViewModel(); 
      categoryVM.Id = i.Id; 
      categoryVM.Title = i.Title; 
      categoriesVM.Add(categoryVM); 
      categoryVM.UsedDescriptions = repo.GetUsedDescriptions(i.Id); 
      categoryVM.UnusedDescriptions = repo.GetUnusedDescriptions(i.Id); 
} 


return Json(categoriesVM); 

雖然categoriesVM對象被正確地構建,我不從它那裏得到適當的JSON對象的某些原因。爲什麼這樣?

+3

「我沒有從它得到適當的Json對象」 - 什麼**具體**是不同/不適當的? –

+1

您可能需要顯示預期的與實際的JSON輸出。 –

+0

你會得到什麼錯誤? – HaBo

回答

1

我建議你輸出的JSON和投入jsonlint.com

這會幫你找出是什麼原因造成的JSON是無效的。這可能與您對Description對象的定義有關,因爲您的CategoriesJsonViewModel看起來應該沒問題。

+0

我如何獲取Json()中生成的JSON? – Bartosz

+0

Firebug清單500內部服務器錯誤 – Bartosz

+0

在你的控制器中確保你有返回的Json(categoriesVM,JsonRequestBehavior.AllowGet) - 你應該能夠看到在Firebug中發回的Json。 – Matt27