Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JsonResult using an ActionFilter on an ActionResult in a controller

Tags:

c#

asp.net-mvc

I want to return the Model (data) of a controller in different formats (JavaScript/XML/JSON/HTML) using ActionFilter's. Here's where I'm at so far:

The ActionFilter:

public class ResultFormatAttribute : ActionFilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuting(ResultExecutingContext context)
    {
        var viewResult = context.Result as ViewResult;

        if (viewResult == null) return;

        context.Result = new JsonResult { Data = viewResult.ViewData.Model };
    }
}

And the it's implementation:

[ResultFormat]
public ActionResult Entries(String format)
{
    var dc = new Models.WeblogDataContext();

    var entries = dc.WeblogEntries.Select(e => e);

    return View(entries);
}

The OnResultExecuting method gets called, but I am not getting the Model (data) returned and formatted as a JSON object. My controller just renders the View.


Update: I am following the suggestion of Darin Dimitrov's answer to this question.

like image 612
cllpse Avatar asked Nov 02 '09 16:11

cllpse


2 Answers

This was what I was looking for:

public class ResultFormatAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        context.Result = new JsonResult
        {
            Data = ((ViewResult)context.Result).ViewData.Model
        };
    }
}
like image 128
cllpse Avatar answered Nov 15 '22 23:11

cllpse


Have you tried implementing your filter code in the OnActionExecuted method, instead of OnResultExecuting? It's possible that by the time the latter is fired, it's too late to change the result (the semantics being, "OK, we have the result in hand, and this hook is fire right before this result right here is executed"), but I don't have the time right now to go check the MVC source to be sure.

like image 34
Sixten Otto Avatar answered Nov 16 '22 00:11

Sixten Otto