MVC常用跳轉頁面的方法


MVC常用跳轉頁面的方法

1、利用View()直接返回視圖(不執行Action方法)

public class HomeController : Controller
{
    public ActionResult Index()
    {
        #region View()的三種寫法
        return View();//返回Index視圖
        return View("Create");//返回Create視圖
        return View("/User/Create");//不能返回User/Create視圖,MVC只檢查Score文件夾(action所在的控制器)及Share文件夾(模板頁)
        #endregion
    }
}

  

2、利用Redirect()跳轉Action

    public ActionResult RedirectJump(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 ActionResult RedirectToActionJump(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()方法 
        return RedirectToAction("Index", "User", new { name = "guoguo", age = "18" });//進入無參或參數均為可空類型的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 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) { }
    });
}

  

更多了解:https://blog.csdn.net/xiaouncle/article/details/83020560

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM