[ASP.NET]WebForm中的MessageBox.Show
我們都知道在Window Form中使用MessageBox.Show可以跳出一個訊息,那在Web Form呢?似乎只能透過ClientScript、Literal、或者Response.Write等方式來跳出警示訊息囉,其實我們也可以把這樣的功能包裝成一個MesageBox的class,下面這段code在網路上應該很多地方都找的到,我自己也忘記是從哪邊找來的了,不過還是分享出來給大家囉:
/// Summary description for MessageBox.
/// </summary>
public class MessageBox
{
private static Hashtable m_executingPages = new Hashtable();
private MessageBox(){}
/// <summary>
/// MessageBox訊息窗
/// </summary>
/// <param name="sMessage">要顯示的訊息</param>
public static void Show( string sMessage )
{
// If this is the first time a page has called this method then
if( !m_executingPages.Contains( HttpContext.Current.Handler ) )
{
// Attempt to cast HttpHandler as a Page.
Page executingPage = HttpContext.Current.Handler as Page;
if( executingPage != null )
{
// Create a Queue to hold one or more messages.
Queue messageQueue = new Queue();
// Add our message to the Queue
messageQueue.Enqueue( sMessage );
// Add our message queue to the hash table. Use our page reference
// (IHttpHandler) as the key.
m_executingPages.Add( HttpContext.Current.Handler, messageQueue );
// Wire up Unload event so that we can inject some JavaScript for the alerts.
executingPage.Unload += new EventHandler( ExecutingPage_Unload );
}
}
else
{
// If were here then the method has allready been called from the executing Page.
// We have allready created a message queue and stored a reference to it in our hastable.
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];
// Add our message to the Queue
queue.Enqueue( sMessage );
}
}
// Our page has finished rendering so lets output the JavaScript to produce the alert's
private static void ExecutingPage_Unload(object sender, EventArgs e)
{
// Get our message queue from the hashtable
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];
if( queue != null )
{
StringBuilder sb = new StringBuilder();
// How many messages have been registered?
int iMsgCount = queue.Count;
// Use StringBuilder to build up our client slide JavaScript.
sb.Append( "<script language='javascript'>" );
// Loop round registered messages
string sMsg;
while( iMsgCount-- > 0 )
{
sMsg = (string) queue.Dequeue();
//sMsg = sMsg.Replace( "\n", "\\n" ); //這部分是我mark掉的
sMsg = sMsg.Replace( "\"", "'" );
//W3c建議要避開的危險字元
//&;`'\"|*?~<>^()[]{}$\n\r
sMsg = sMsg.Replace( "\n", "_" );
sMsg = sMsg.Replace( "\r", "_" );
sb.Append( @"alert( """ + sMsg + @""" );" );
}
// Close our JS
sb.Append( @"</script>" );
// Were done, so remove our page reference from the hashtable
m_executingPages.Remove( HttpContext.Current.Handler );
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write( sb.ToString() );
}
}
}
使用的方法很簡單,用法跟Window Form中一樣,使用MessageBox.Show就能呼叫囉,使用此方法,script會被render在</html>之後,所以這個alert會在html render完之後,但在body onload前執行。
這個用法在部分套用UpdatePanel的時候會出先一些錯誤,因為UpdatePanel搭配Response.Write是會有問題的,這時候我們可以幫Show多一個多載,大概長的像這樣:
{
ScriptManager.RegisterClientScriptBlock(pPage, typeof(Page), "alert", "<script>alert('" + sMessage + "');</script>", false);
}
透過ScriptManager來註冊script,這就不會錯囉。
備註:其實Show這個function透過ClientScript來註冊script也是OK的,但因為上面的class使用上沒什麼大問題,我也沒有去修改它了,其實使用RegisterStartupScript與RegisterClientBlock來註冊還能有效的決定執行的順序呢,細節可以看這篇:RegisterStartupScript跟RegisterClientScriptBlock的差別。
游舒帆 (gipi) 探索原力Co-founder,曾任TutorABC協理與鼎新電腦總監,並曾獲選兩屆微軟最有價值專家 ( MVP ),離開職場後創辦探索原力,致力於協助青少年培養面對未來的能力。認為教育與組織育才其實息息相關,都是在為未來儲備能量,2018年起成立為期一年的專題課程《職涯躍升的關鍵24堂課》,為培養台灣未來的領袖而努力。 |