2012-11-01 83 views
2

我想返回從ASP.NET MVC的ActionResult類型方法的JSON看起來是這樣的:JSON格式在ASP.NET MVC

{ 
    success: true, 
    users: [ 
    {id: 1, FileName: 'Text22'}, 
    {id: 2, FileName: 'Text23'} 
    ] 
} 

我將如何格式化?現在我有這樣的東西

Return Json(New With {Key .success = "true", Key .users = responseJsonString}, JsonRequestBehavior.AllowGet) 

編輯:我使用VB.NET,但在C#中的答案也很好。

回答

5

我更喜歡使用ViewModels,而不是手動構建複雜的JSON響應。它確保了所有返回數據的方法的一致性,並且更容易使用強類型的屬性恕我直言。

public class Response 
{ 
    public bool Success { get; set; } 
    public IEnumerable<User> Users { get; set; } 
} 

public class User 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

,然後只是:

Response response = new Response(); 
response.Success = true; 
// populate the rest of the data 

return Json(response); 

這也有讓您使用一個基類爲每一個反應,如果有類似的成功狀態,或錯誤信息的公共數據的優勢。

public class ResponseBase 
{ 
    public bool Success { get; set; } 
    public string Message { get; set; } 
} 

public class UserResponse : ResponseBase 
{ 
    IENumerable<User> Users { get; set } 
} 

現在,如果你有一個錯誤:

return Json(new ResponseBase() { Success = false, Message = "your error" }); 

,或者如果它成功

return Json(new UserResponse() { Success = true, Users = users }); 

如果你想手動工藝的JSON,然後只是:

return Json(new { success = true, users = new[] { new { id = 1, Name = "Alice"}, new { id = 2, Name = "Bob"} } }); 
+0

只是我正在尋找的解釋,謝謝! –

1
在C#

return Json(new 
    { 
     success = true, 
     users = new[] 
      { 
       new {id = 1, FileName = "Text22"}, new {id = 2, FileName = "Text23"} 
      } 
    }, JsonRequestBehavior.AllowGet); 

返回

{ 「成功」:真, 「用戶」:[{ 「ID」:1, 「文件名」: 「Text22」},{ 「ID」 :2,「FileName」:「Text23」}]}