MVC中常用的跳转方法

时间:2023-03-09 03:12:32
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 = ,name = "刘备" });
}
    注:也可以通过 Return View("XXX")的方式跳转

3.过滤器中的跳转

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

     public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!hasAuthority)
{
filterContext.Result = new RedirectResult("/Home/Index");
}
base.OnActionExecuting(filterContext);
}