繁体   English   中英

ASP.NET MVC:构建Json ActionResult的最佳C#方法

[英]ASP.NET MVC: Best C# method of building a Json ActionResult

过去也曾提出类似的问题,但现在看起来有点过时了。 我试图获得目前关于在ASP.NET MVC中构造JsonResult的最佳方法的一致意见。 此问题的上下文是使用.NET 4 / 4.5和MVC 4中提供的最新方法

这是我多年来遇到的一些流行方法:

var json1 = new { foo = 123, bar = "abc" };

var json2 = new Dictionary<string, object>{ { "foo", 123 }, { "bar", "abc" } };

dynamic json3;
json3.foo = 123;
json3.bar = "abc";

还请解释您首选方法的优缺点

我个人用这个:

public class MyViewModel
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

接着:

public ActionResult Foo()
{
    var model = new MyViewModel
    {
        Foo = 123,
        Bar = "abc"
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

优点:

  • 强大的打字
  • 没有魔法字符串
  • 重构友好
  • 单元测试友好
  • 代码很容易转换为新的Web Api控制器动作调用,保持前面的点是真的:

     public class ValuesController: ApiController { public MyViewModel Foo() { return new MyViewModel { Foo = 123, Bar = "abc" }; } } 

缺点:尚未遇到过。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM