更改视图在一个ASP.NET MVC过滤器 [英] Changing the view in an ASP.NET MVC Filter

查看:237
本文介绍了更改视图在一个ASP.NET MVC过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,如果他们使用的是手机浏览器将用户重定向到一个不同的看法。我已经决定,我想做到这一点使用MVC过滤器通过其应用到我想有一个移动视图操作。

我相信这重定向需要OnActionExecuted发生,但是filterContext不包含视图的信息 - 但它确实在OnResultExecuted,但这个时候,我相信这是来不及更改视图

我怎么能拦截视图名称和更改的ViewResult?

这是我在执行的结果,并希望我有行动的工作时执行。

 公共类MobilePageFilter:ActionFilterAttribute
{
    公共覆盖无效OnResultExecuted(ResultExecutedContext filterContext)
    {
        如果(filterContext.Result是的ViewResult)
        {
            如果(isMobileSite(filterContext.HttpContext.Session [SetMobile.SESSION_USE_MOBILE]))
            {
                的ViewResult的ViewResult =(的ViewResult)filterContext.Result;                字符串的viewName = viewResult.ViewName;
                filterContext.Result =新的ViewResult
                {
                    VIEWNAME =移动/+的viewName,
                    ViewData的= viewResult.ViewData,
                    TempData的= viewResult.TempData
                };
            }
        }        base.OnResultExecuted(filterContext);
    }
}


解决方案

我会建议你以下博客文章这也解释了一个更好的选择,以达到你所要求的是什么,而不是使用动作过滤器。

I want to redirect the user to a different view if they are using a mobile browser. I've decided I'd like to do this using MVC filters by applying it to actions which I want to have a mobile view.

I believe this redirect needs to happen in OnActionExecuted, however the filterContext does not contain information on the view - it does, however in OnResultExecuted, but by this time I believe it is too late to change the view.

How can I intercept the view name and change the ViewResult?

This is what I have in the result executed and what I'd like to have work in Action Executed.

public class MobilePageFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if(filterContext.Result is ViewResult)
        {
            if (isMobileSite(filterContext.HttpContext.Session[SetMobile.SESSION_USE_MOBILE]))
            {
                ViewResult viewResult = (ViewResult)filterContext.Result;

                string viewName = viewResult.ViewName;
                filterContext.Result = new ViewResult
                {
                    ViewName = "Mobile/" + viewName,
                    ViewData = viewResult.ViewData,
                    TempData = viewResult.TempData
                };
            }
        }

        base.OnResultExecuted(filterContext);
    }
}

解决方案

I would recommend you the following blog post which explains a better alternative to achieve what you are asking for rather than using action filters.

这篇关于更改视图在一个ASP.NET MVC过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆