MVC中常用的跳转方法

MVC中常用的跳转方法

这里总结了几种MVC中的跳转方式,主要汇总了前端页面跳转,后台的跳转,和过滤器中的跳转方式。

1.在前端页面的跳转方式

<!--属性形式--->
<a href="@Url.Action("ActionName","ControllerName",new{p1=1,p2=2})">跳转到Test</a>
<!--标签形式--->
@Html.ActionLink("跳转到Test", "ActionName", "ControllerName", new { p1 = 1, p2 = 2 }, null)

2.在后台通过ActionResult跳转

    public ActionResult GetRedirect(int id)
        {
            //return RedirectToAction("ActionName","ControllerName");
            //return RedirectToAction("ActionName","ControllerName",new { name="hello"});
           return RedirectToRoute(new { controller = "Home", action = "Index", id = 1,name = "刘备" }); 
        }
    注:也可以通过 Return View("XXX")的方式跳转

3.过滤器中的跳转

  如果在Filter中用Response.Redirect,虽然URL是跳转了,但是之后的Filter和Action还是会执行。这是因为过滤器必须获取一个filterContext.Result才会停止,为了在跳转时不再执行后续的FIlter和Action,我们必须要赋值filterContext.Result。

1     public override void OnActionExecuting(ActionExecutingContext filterContext)
2         {
3             if (!hasAuthority)
4             {
5                 filterContext.Result = new RedirectResult("/Home/Index");
6             }
7             base.OnActionExecuting(filterContext);
8         }

 

posted @ 2018-07-04 11:05  捞月亮的猴子  阅读(1235)  评论(0编辑  收藏  举报