[英]ASP.NET MVC: Best C# method of building a Json ActionResult
Similar questions have been asked in the past, but they seem a little dated now. 过去也曾提出类似的问题,但现在看起来有点过时了。 I'm trying to get the current general consensus on what's the best way to construct a JsonResult in ASP.NET MVC. 我试图获得目前关于在ASP.NET MVC中构造JsonResult的最佳方法的一致意见。 The context of this question is to use the most current methods available from .NET 4/4.5 & MVC 4 此问题的上下文是使用.NET 4 / 4.5和MVC 4中提供的最新方法
Here's a few popular methods I've come across over the years: 这是我多年来遇到的一些流行方法:
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";
Please also the explain the pros/cons of your preferred method 还请解释您首选方法的优缺点
Personally I use this one: 我个人用这个:
public class MyViewModel
{
public int Foo { get; set; }
public string Bar { get; set; }
}
and then: 接着:
public ActionResult Foo()
{
var model = new MyViewModel
{
Foo = 123,
Bar = "abc"
};
return Json(model, JsonRequestBehavior.AllowGet);
}
Pros: 优点:
the code is perfectly easily transposable to a new Web Api controller action call keeping the previous points true: 代码很容易转换为新的Web Api控制器动作调用,保持前面的点是真的:
public class ValuesController: ApiController { public MyViewModel Foo() { return new MyViewModel { Foo = 123, Bar = "abc" }; } }
Cons: haven't encountered one yet. 缺点:尚未遇到过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.