gmartinez
gmartinez

Reputation: 11

Which is the best option to send json using mvc4?

I would like to know which of these options is the best in order to return a json object using C#:

Option 1:

public EmptyResult GetImages() {
    /*operations*/
    ControllerContext.HttpContext.Response.AddHeader("content-type", "application/json");
    ControllerContext.HttpContext.Response.Write(JsonConvert.SerializeObject(images));
    return new EmptyResult();
}

or option 2:

public EmptyResult GetImages() {
    /*operations*/
    return Json(images);
}

Upvotes: 0

Views: 119

Answers (2)

keeehlan
keeehlan

Reputation: 8054

In my experience, it's definitely this:

public JsonResult GetImages() 
{
    //operations
    return Json(images);
}

Upvotes: 4

Lars Anundskås
Lars Anundskås

Reputation: 1355

Your best option is taking use of the great framework made just for these needs; WebAPI

Create an Api Controller

public class ApiTestController : ApiController
{
    public IEnumerable<Image> GetImages()
    {
        return yourDataAccess.GetAllImages()                            
    }
}

Upvotes: 5

Related Questions