本文介绍了返回使用JsonResult的ActionFilter上一个ActionResult在控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要回以不同的格式(的JavaScript / XML / JSON / HTML)使用ActionFilter的控制器的模型(数据)。下面是我在哪里至今:

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:

该ActionFilter:

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

而它的实现:

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

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

    return View(entries);
}

OnResultExecuting 方法被调用,但我没有得到的模型(数据)返回,并格式化为一个JSON对象。我刚才控制器呈现视图。




更新:我达林季米特洛夫的回答的建议,this问题。

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.

推荐答案

这就是我一直在寻找:

public class ResultFormatAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        context.Result = new JsonResult
        {
            Data = ((ViewResult)context.Result).ViewData.Model
        };
    }
}

这篇关于返回使用JsonResult的ActionFilter上一个ActionResult在控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 03:56