asp.net - 在 ASP.NET MVC 中格式化 JSON

标签 asp.net asp.net-mvc json

我想从 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/

相关文章:

c# - ASP.NET 将图片添加到 TableCell

c# - 在 silverlight 项目中引用 asp.net c# 类/方法

asp.net-mvc - 在没有回发控制的情况下保留某些值的最安全方法是什么

javascript - 如何使用 JavaScript 生成复杂 JSON 对象的某些元素的 CSV 文件?

javascript - 只需使用 javascript 即可通过用户输入查询基于 JSON 的 API

c# - LINQ to Entities 无法识别 Replace 方法?

asp.net - 如何最好地检测 ASP.NET 过期 session ?

asp.net-mvc - WebGrid 未显示

c# - 在 <p> 标记内渲染时删除冗余空格

c++ - 使用 JSON Spirit 进行 pretty-print