轉---在ASP.NET MVC中實現登入後回到原先的介面

來源:互聯網
上載者:User

標籤:

有這樣的一個需求:提交表單,如果使用者沒有登入,就跳轉到登入頁,登入後,跳轉到原先表單提交這個頁面,而且需要保持提交表單介面的資料。

 

提交表單的頁面是一個強型別視圖頁,如果不考慮需要保持提交表單介面的資料,可以先設計這樣的一個Model:

 

public class Student
{
    public string Name{get;set;}
    public string ReturnUrl{get;set;}
}

 

在提交表單的視圖頁,大致這麼寫:

 

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.Hidden("ReturnUrl", Request.Url.PathAndQuery)
    @Html.TextBoxFor(m => m.Name)
    <input type="submit" value="提交"/>
}

 

在控制器中大致這麼寫:

 

public ActionResult Index()
{
    return View(new Student());
}

 
[HttpPost]
public ActionResult Index(Student student)
{
    return Redirect(student.ReturnUrl);
}

 

可是,雖然回到了表單提交的強型別視圖頁,表單資料卻沒有得以保持。

 

於是,想到了使用如下方式:

return View("someview", somemodel);

 

someview的名稱如何擷取呢?

 

public ActionResult Index()
{
    return View(new Student());
}

以上,如果我們擷取到action的名稱就相當於擷取到視圖的名稱!

 

重新設計Model:

 

    public class Student
    {
        public string Name { get; set; }
        public string ControllerName { get; set; }
        public string ActionName { get; set; }
    }

 

可以先從路由中把action名稱拿到,然後賦值給Student的ActionName屬性。

 

    public class HomeController : Controller
    {
        
        public ActionResult Index()
        {
            Student student = new Student()
            {
                ActionName = this.ControllerContext.RouteData.Values["action"].ToString(),
                ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString()
            };
            return View(student);
        }

 
        [HttpPost]
        public ActionResult Index(Student student)
        {
            ViewBag.msg = "我又回來了~~";
            //如果是登入,先驗證,驗證成功執行下面的代碼
            return View(student.ActionName, student);
        }

 
    }    

以上,student.ActionName值既是action名稱也是view名稱。

 

在提交表單的強型別視圖頁:

 

@model MvcApplication1.Models.Student

 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 
<h2>Index</h2>

 
<div>@ViewBag.msg</div>

 
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.Name)
    <input type="submit" value="提交"/>
}

 

所以,面對本篇開始描述的需求,僅僅跳轉是不夠的,需要向某個視圖傳遞Model,而其中的關鍵是:
1、從路由中擷取action名稱
2、action名稱和view名稱一致  

轉---在ASP.NET MVC中實現登入後回到原先的介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.