![](/img/trans.png)
[英]Master Page is getting called twice in Response.Redirect asp.net c#
[英]Bypass ASP.NET master page rendering after Response.Redirect(url, false)
我正在嘗試使用我的母版頁的代碼隱藏來在重定向后向用戶顯示消息。 特別,
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["redirect_message"] != null)
{
// put the message in a hidden field for JavaScript to put in an alert()
Session.Remove("redirect_message");
}
}
}
然后,任何想要顯示消息的頁面都可以執行此操作:
Session["redirect_message"] = "I've sent you to OtherPage.aspx";
Response.Redirect("~/OtherPage.aspx");
這是我想要的方式...我首先得到OtherPage.aspx
的Page_Load
事件,然后我得到了主人的Page_Load
事件。 但是,我在許多地方(比如這里 )讀到這種重定向方式是不可取的。 所以,我改為推薦的方式:
Session["redirect_message"] = "I've sent you (nicely this time) to OtherPage.aspx";
Response.Redirect("~/OtherPage.aspx", false); // don't use Response.End()
Context.Application.CompleteRequest();
不幸的是,現在我的母版頁面的Page_Load
事件在 OtherPage.aspx
開始加載之前被調用。 我從這個響應中看到,沒有好辦法停止處理頁面(除了使用MVC,這對我來說不是一個選項) - 有沒有辦法至少阻止主頁控件加載?
這是一種方法,但它的適用性有些限制,看起來非常不優雅。 如果我可以決定在Page_PreInit
事件中重定向,我可以用另一個不處理Session["redirect_message"]
變量的母版頁替換母版頁:
public partial class FirstPage : Page {
private bool redirected = false;
protected void Page_PreInit(object sender, EventArgs e) {
if (redirect_condition_is_true) {
Session["redirect_message"] = "I've sent you (nicely this time) to OtherPage.aspx";
MasterPageFile = "~/Redirect.master";
Response.Redirect("~/OtherPage.aspx", false); // don't use Response.End()
Context.Application.CompleteRequest();
}
}
protected void Page_Load(object sender, EventArgs e) {
// for all Page events we're processing, start with:
if (redirected) {
return;
}
}
}
你不能只做MasterPageFile = null
,因為頁面的元素正在尋找母版頁。 您必須在PreInit
上執行此操作,因為這是您最后一次更改母版頁。 備用母版頁必須具有在啟動重定向的頁面中引用的所有ContentPlaceHolder
元素,並且如果頁面具有ScriptManager
則還必須指定ScriptManagerProxy
。 就像我說的那樣,不是非常優雅......還在尋找更好的東西。
編輯
我想出了一個更好的方法。 我沒有使用母版頁的代碼隱藏,而是實現了一個包含我正在尋找的行為的Page
的子類,然后任何一個重定向目標的頁面都繼承自該子類。 所以:
public class BasePage : System.Web.UI.Page {
protected virtual void Page_Load(object sender, EventArgs e) {
if (Session["redirect_message"] != null) {
ClientScript.RegisterStartupScript(GetType(), "redirect_message",
String.Format("alert('{0}');", (string)Session["redirect_message"]),
true);
Session.Remove("redirect_message");
}
}
}
和
public class OtherPage : BasePage {
protected override void Page_Load(object sender, EventArgs e) {
base.Page_Load(sender, e);
// page-specifc logic here
}
}
然后當我重定向時,我使用:
Session["redirect_message"] = "I've sent you (nicely this time) to OtherPage.aspx";
Response.Redirect("~/OtherPage.aspx", false); // don't use Response.End()
Context.Application.CompleteRequest();
擁有基類還允許我將其他常用功能放在一個類中。 歡迎評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.