[ASP.NET]WebForm中的MessageBox.Show

我們都知道在Window Form中使用MessageBox.Show可以跳出一個訊息,那在Web Form呢?似乎只能透過ClientScript、Literal、或者Response.Write等方式來跳出警示訊息囉,其實我們也可以把這樣的功能包裝成一個MesageBox的class,下面這段code在網路上應該很多地方都找的到,我自己也忘記是從哪邊找來的了,不過還是分享出來給大家囉: view sourceprint?01 /// 02 /// Summary description for MessageBox. 03 /// 04 public class MessageBox 05 { 06 private static Hashtable m_executingPages = new Hashtable(); 07 private MessageBox(){} 08 /// 09 /// MessageBox訊息窗 10 /// 11 /// 要顯示的訊息 12 public static void Show( string sMessage ) 13 { 14 // If this is the first time a page has called this method then 15 if( !m_executingPages.Contains( HttpContext.Current.Handler ) ) 16 { 17 // Attempt to cast HttpHandler as a Page. 18 Page executingPage = HttpContext.Current.Handler as Page; 19 if( executingPage != null ) 20 { 21 // Create a Queue to hold one or more messages. 22 Queue messageQueue = new Queue(); 23 // Add our message to the Queue 24 messageQueue.Enqueue( sMessage ); 25 26 // Add our message queue to the hash table. Use our page reference 27 // (IHttpHandler) as the key. 28 m_executingPages.Add( HttpContext.Current.Handler, messageQueue ); 29 // Wire up Unload event so that we can inject some JavaScript for the alerts. 30 executingPage.Unload += new EventHandler( ExecutingPage_Unload ); 31 } 32 } 33 else 34 { 35 // If were here then the method has allready been called from the executing Page. 36 // We have allready created a message queue and stored a reference to it in our hastable. 37 Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ]; 38 39 // Add our message to the Queue 40 queue.Enqueue( sMessage ); 41 } 42 } 43 // Our page has finished rendering so lets output the JavaScript to produce the alert's 44 private static void ExecutingPage_Unload(object sender, EventArgs e) 45 { 46 // Get our message queue from the hashtable 47 Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ]; 48 49 if( queue != null ) 50 { 51 StringBuilder sb = new StringBuilder(); 52 // How many messages have been registered? 53 int iMsgCount = queue.Count; 54 // Use StringBuilder to build up our client slide JavaScript. 55 sb.Append( "", false); 4 } 透過ScriptManager來註冊script,這就不會錯囉。 備註:其實Show這個function透過ClientScript來註冊script也是OK的,但因為上面的class使用上沒什麼大問題,我也沒有去修改它了,其實使用RegisterStartupScript與RegisterClientBlock來註冊還能有效的決定執行的順序呢,細節可以看這篇:RegisterStartupScript跟RegisterClientScriptBlock的差別。

你可能感兴趣的:(JavaScript,null,Class,webform,asp.net,reference)