2012-12-15 17 views
1

ASP.NET MVC2視圖:如何解決孩子的行爲是不允許進行重定向操作,其他的答案不能解決

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.PaymentViewModel>" %> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    ... 
    <form action="<%= Html.Action("PaymentByBankTransfer", "Checkout") %>" > 
    <input type="submit" value="Payment by bank transfer" /> 
    </form> 

CheckoutController:

public ActionResult PaymentByBankTransfer() 
    { 
     var order = Session["Order"] as Order; 
     ExecCommand(@"update dok set confirmed=true where order={0}", order.OrderId); 
     return CheckoutCompleteOK(); 

     var cart = ShoppingCart.GetCart(HttpContext); 
     cart.EmptyCart(); 
     // https://stackoverflow.com/questions/1538523/how-to-get-an-asp-net-mvc-ajax-response-to-redirect-to-new-page-instead-of-inser?lq=1 
     return JavaScript("window.location = '/Checkout/CompleteOK'"); 
    } 

    // common method called from other controller methods also 
    public ActionResult CheckoutCompleteOK() 
    { 
     var cart = ShoppingCart.GetCart(HttpContext); 
     cart.EmptyCart(); 
     // prevent duplicate submit if user presses F5 
     return RedirectToAction("Complete"); 
    } 

    public ActionResult Complete() 
    { 
     var order = Session["Order"] as Order; 
     SendConfirmation(order); 
     return View("PaymentComplete", order); 
    } 

按下表單提交按鈕會導致異常

Child actions are not allowed to perform redirect actions 

由於代碼顯示來自

的最高答案答案

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

試圖修復它,但是這會導致其他錯誤:瀏覽器嘗試打開URL window.location = '/Checkout/CompleteOK'

如何解決這個異常?一切看起來都很好,沒有其他答案中描述的部分視圖。 我試過在表單中​​使用method ='post'屬性,但問題仍然存在。

+0

這與您的問題無關,但是您是否意識到在您的PaymentByBankTransfer操作中,第一次返回後的代碼無法訪問? – Romias

+0

是的。第一次返回後的代碼顯示了使用其他參考答案中的代碼解決問題的另一個不成功的嘗試。最好避免這種javascipt注射,首先返回應該工作。我問爲什麼第一次返回導致這個stange錯誤,可能在RedirectToAction方法調用 – Andrus

+0

你試過'返回RedirectToAction(「完成」);'直接從'PaymentByBankTransfer()'?你是否有同樣的錯誤,或者你是否達到了預期的行爲? –

回答

3

而不是在發佈後調用public ActionResult CheckoutCompleteOK(),刪除該操作併爲public ActionResult PaymentByBankTransfer()創建HTTP發佈操作。

然後在PaymentByBankTransfer post方法中返回RedirectToAction("Complete");

我認爲這會解決您的問題。

4

不使用JavaScript重定向爲: 如果你把表格你的孩子視圖中,有時候,如果你指定Beginform幫手(子視圖內)操作名稱和控制器的名稱,這個問題不會發生。比如我改變了我的孩子動作看法是這樣的:

前:

@using (Html.BeginForm()) 
{ 
... 
} 

後:

@using (Html.BeginForm("InsertComment", "Comments", FormMethod.Post, new { id = "commentform" })) 
{ 
... 
} 

現在,你可以把RedirectAction命令裏面的 「InsertComment」 行動,一切都將正常工作。

相關問題