简体   繁体   中英

Return JsonResult using an ActionFilter on an ActionResult in a controller

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.

Have you tried:

return Json(entries);

with a return type of JsonResult on the controller action?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM