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. The context of this question is to use the most current methods available from .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
Although MVC has more benefits, it also requires greater expertise to implement. Therefore, the nature of the application and the development team play a factor in which to use. MVC is generally preferable when the project size is larger and requires a faster development cycle.
MVC stands for Model, View, and Controller. MVC separates an application into three components - Model, View, and Controller. Model: Model represents the shape of the data. A class in C# is used to describe a model.
And in this case, ASP.NET Core is much faster than ASP.NET MVC and has shown great results compared to other frameworks. A reason for the framework's quick performance is the fact that the system automatically optimizes its codes to improve performance.
. NET Framework is an object oriented programming framework meant to be used with languages that it provides bindings for. Since C is not an object oriented language it wouldn't make sense to use it with the framework.
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:
public class ValuesController: ApiController
{
public MyViewModel Foo()
{
return new MyViewModel
{
Foo = 123,
Bar = "abc"
};
}
}
Cons: haven't encountered one yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With