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.
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
};
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With