Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 551
Didaxis Avatar asked Jul 18 '12 16:07

Didaxis


People also ask

Which one is best ASP.NET or MVC?

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.

Does MVC use C#?

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.

Is .NET Core faster than MVC?

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.

Can I use .NET with C?

. 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.


1 Answers

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:

  • strong typing
  • no magic strings
  • refactor friendly
  • unit test friendly
  • 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.

like image 149
Darin Dimitrov Avatar answered Sep 23 '22 08:09

Darin Dimitrov