2009-09-02 56 views
3

想象一下,我在頁面上有一個子表單的場景。此子表單包含在部分用戶控件中,併發布到其自己的專用控制器操作中。如果違反商業規則,我想返回用戶以前的相同視圖。asp.net mvc - 如何將用戶返回到上一個操作?

實施例:

  • 用戶是在/示例/第1頁這使得局部 「SignOnForm」
  • 點登錄表單提交到 「帳戶/點登錄」。
  • 如果某些東西無效,我想將用戶返回到帶有模型狀態的/ example/page1。但是,我無法硬編碼視圖,因爲用戶可能位於不同的頁面上,例如/ othercontroller/page10。

回答

0
public SignOn(string username, string password) 
{ 
    //login logic here 
    ... 

    //Now check if the user is authenticated. 
    if(User.IsAuthenticated) 
    { 
    //Redirect to the next page 
    return RedirectToAction("page10", "Other"); 
    } 
    else 
    { 
    // You could also pass things such as a message indicating the user was not authenticated. 
    return RedirectToAction("page1", "Example"); 
    } 
} 

而且,你總是可以轉儲從最後一個「好」的發佈頁面的表單數據到隱藏的表單字段,並讓用戶點擊「返回」按鈕,從而有效地向前它們發佈到上一頁。我不特別喜歡這個,因爲這意味着你必須保持以前的表單域。

2

您可以使用請求查詢字符串一直通過SignOn進程返回URL。

首先,指定頁面返回時,你使您的點登錄偏:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
<%@ Import Namespace="Microsoft.Web.Mvc"%> 

<!-- Your Example/Page1 page --> 

<% if (!User.IsAuthenticated) %> 
    <%= Html.RenderAction("SignOn", "Account", new { returnUrl = Request.Url.PathAndQuery }); %> 

使用如的RenderAction當前上下文是不是賬戶控制器。該功能目前不在MVC版本中,因此您需要在解決方案中包含ASP.NET MVC's Future library

接下來,點登錄控制器:

public ActionResult SignOn(string returnUrl) 
{ 
    if (User.Identity.IsAuthenticated) 
    { 
     User user = userRepository.GetItem(u => u.aspnet_UserName == User.Identity.Name); 
     return !string.IsNullOrEmpty(returnUrl) 
       ? Redirect(returnUrl) 
       : (ActionResult) RedirectToAction("Index", "Home"); 
    } 
    return PartialView(); 
} 

點登錄形式:

<% using (Html.BeginForm("SignOn", "Account", new { returnUrl = Request.QueryString["returnUrl"] },FormMethod.Post,new {@class="my_signOn_class"})) 
    { %> 
     <!-- Form --> 
<% } %> 

最後,在你點登錄控制器處理表單POST,您可以將用戶返回到 'RETURNURL' 使用以下代碼:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult SignOn(FormCollection formCollection, string returnUrl) 
{ 
    if (BusinessRuleViolated(formCollection)) 
    { 
     if(!string.IsNullOrEmpty(returnUrl)) 
     { 
      return Redirect(returnUrl); 
     } 
     return RedirectToAction("Index", "Home"); 
    } 

    // SignIn(...) 
} 
相關問題