ASP.NET MVC: C # Best Method for Creating Json ActionResult

Similar questions have been asked in the past, but they seem to be a bit from now on. I am trying to get general consensus on the best way to create JsonResult in ASP.NET MVC. The context of this question is to use the most advanced methods available from .NET 4 / 4.5 and MVC 4

Here are some 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"; 

Also explain the advantages / disadvantages of your preferred method.

+6
source share
1 answer

Personally, I use this:

 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:

  • strong typing
  • no magic lines
  • refactor friendly
  • unit test friendly
  • the code can be easily transferred to a new call to the Web Api controller action, keeping the previous points true:

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

Cons: not yet met.

+18
source

Source: https://habr.com/ru/post/920816/


All Articles