tags:

views:

371

answers:

3

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.

+1  A: 

Have you tried:

return Json(entries);

with a return type of JsonResult on the controller action?

jamesaharvey
IResultFilter.OnResultExecuting returns Void. And the Json class is not available in that context.
roosteronacid
+1  A: 

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.

Sixten Otto
A: 

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
        };
    }
}
roosteronacid