C# MVC 后台或前端页面跳转Action的常用方法

1、利用View()直接返回视图(不执行Action方法)

public class ScoreController : Controller
{
    public ActionResult Index(string name, int age)
    {
        #region View()的三种写法
        return View();//返回Index视图
        return View("Create");//返回Create视图
        return View("/User/Create");//不能返回User/Create视图,MVC只检查Score文件夹(action所在的控制器)及Share文件夹(模板页)
        #endregion
    }
}


2、利用Redirect()跳转Action

public class ScoreController : Controller
{
    public ActionResult Index(string name, int age)
    {
        #region Redirect()的四种写法
        return Redirect("Index");//进入无参或参数均为可空类型的Index()方法,并开始死循环
        return Redirect("Index?age=16");//若Index()存在不可空类型的参数则必须传递参数值,后两项若存在不可空类型的参数可参照此解决方法
        return Redirect("Create");//进入无参或参数均为可空类型的Create()方法
        return Redirect("/User/Index");//进入无参或参数均为可空类型的User/Index()方法 
        #endregion
    }
}


3、利用RedirectToAction()跳转Action

public class ScoreController : Controller
{
    public ActionResult Index(string name, int age)
    {
        #region RedirectToAction()的四种写法
        return RedirectToAction("Index", "Score");//进入无参或参数均为可空类型的Index()方法 
        return RedirectToAction("Index", "Score", new
        {
            name = "guo",
            age = 16
        });//若Index()存在不可空类型的参数则必须传递参数值,后两项若存在不可空类型的参数可参照此解决方法
        return RedirectToAction("Create", "Score");//进入无参或参数均为可空类型的Create()方法 
        return RedirectToAction("Index", "User");//进入无参或参数均为可空类型的User/Index()方法 
        #endregion
    }
}


4、通过href进行跳转

前台用href='/Home/Logout'请求,后台使用Redirect()、RedirectToAction()进行控制跳转 。

<a href="/Home/Logout" class="easyui-linkbutton" plain="true" iconCls="icon-power-blue">退出</a>
public class HomeController : Controller
{
    public ActionResult Logout()
    {
        Session.Abandon();
        return Redirect("/Login/Index");
        //return RedirectToAction("Index", "Login");
    }
}


5、通过ajax进行跳转
如果前台使用了ajax发起请求,那就只能在success:function(data){ }中进行页面跳转了,后台写的return View()、return Redirect()、return RedirectToAction()最多只能执行Action,不会跳转页面。

function logout() {
    alert("logout()");
    $.ajax({
        type: "post",
        url: "/Home/Logout",
        success: function (data) {
            //window.location.href = '/Login/Index';
            window.location.href = '@Url.Action("Index", "Login")';                    
        },
        error: function (err) { }
    });
}

 

public class HomeController : Controller
{
    public ActionResult Logout()
    {
        Session.Abandon();
        return Redirect("/Login/Index");
        //return RedirectToAction("Index", "Login");
        //return View("/Login/Index");
    }
}
 


原文:https://blog.csdn.net/xiaouncle/article/details/83020560 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值