我想从 ASP.NET MVC ActionResult 类型方法返回一个 JSON,如下所示:
{
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# 中的答案也很好。
最佳答案
我更喜欢使用 ViewModel,而不是手动构建复杂的 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"} } });
关于asp.net - 在 ASP.NET MVC 中格式化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183658/