2017-04-27 146 views
0

我想顯示一個警告用戶在C#重定向頁面

我試圖

System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", "alert('Data has been saved and submitted');", true); 
Page.Response.Redirect(Page.Request.Url.ToString()); 

頁面被重定向後刷新頁面,但我沒有得到警報

我也試過

System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", "var r = confirm('Data has been saved and submitted confirm'); if (r == true) { <%#namespace.project.class().PageRefresh()%> } else { <%#new namespace.project.class().PageRefresh()%> } ", true); 

public void PageRefresh() { 

      Page.Response.Redirect(Page.Request.Url.ToString()); 
     } 

在這種情況下,我得到警報,但重裝不發生

我不想使用客戶端頁面刷新,像那些低於

location.reload(true) 
window.location.href = window.location.href 

我想用

Page.Response.Redirect(Page.Request.Url.ToString()); 

但應提醒用戶

+2

不可能的。如果你思考C#的2行,你建議你很快就會明白爲什麼它不起作用。 –

+0

如果查看代碼是不夠的,請加載Fiddler並查看這些代碼實際執行的操作。 –

回答

1

後執行爲什麼第一次嘗試不起作用:在請求過程中,您正在註冊一個新腳本,然後告訴IIS執行重定向,腳本頁面不會返回給用戶,只是重定向,因爲它是需要的d在IIS級別,而不是瀏覽器。

爲什麼第二次嘗試不起作用:您正試圖將c#代碼注入客戶端腳本之後頁面已編譯。所以<%#...%>將不會被編譯,它會看起來像在結果標記中,你可以使用瀏覽器元素檢查器查看結果代碼,這將證明它。

雖然您不想這樣做,但它應該在客戶端實現,因爲頁面在呈現後和頁面發佈之前不會調用c#後端代碼。其實,你可以用不同的方式實現它:

第一種方法是註冊所需的alert腳本,並在其後立即重新加載。當alert中斷頁面執行時,用戶將不會被重定向,直到他沒有在警報窗口中按OK。這種方式簡單易懂。

System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", "alert('Data has been saved and submitted'); location.reload(true);", true); 

另一種方式是alert後進行形式submit並實現重定向服務器端,因爲你不想寫一些JS。

System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", "alert('Data has been saved and submitted'); document.forms[0].submit();", true); 

,並在Page_Load事件:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (this.IsPostBack) 
    { 
     Page.Response.Redirect(Page.Request.Url.ToString()); 
    } 
}