Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a Json object from Action Attribute?

Tags:

asp.net-mvc

when overriding OnActionExecuting, how do I return a Json result without passing to action?

like image 539
zsharp Avatar asked Apr 20 '10 20:04

zsharp


People also ask

What is the correct way to return JSON objects from action methods in ASP NET MVC?

In your action method, return Json(object) to return JSON to your page. SomeMethod would be a javascript method that then evaluates the Json object returned. ContentResult by default returns a text/plain as its contentType.

Can we return JSON through Viewresult?

You just have toinclude html(view) as one of the property in your json data. @Zach Yes, It's possible. You can return your html with model. Create a partial view and return the partial view with model instead of json result.


1 Answers

I find it useful to use Json.NET to generate the json output. This has many advantages, for example JSON properties can be hidden under certain conditions.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (/* whatever */)
    {
        var result = new ResultModel(); // your json model
        ContentResult content = new ContentResult();
        content.ContentType = "application/json";
        content.Content = JsonConvert.SerializeObject(result);
        filterContext.Result = content;
        base.OnActionExecuting(filterContext);
    }
}
like image 157
mulllhausen Avatar answered Sep 30 '22 10:09

mulllhausen