[ASP.NET]WebForm中的MessageBox.Show

这篇博客介绍了如何在ASP.NET的WebForm中实现类似Window Form中的MessageBox.Show功能。作者提供了一个名为MessageBox的静态类,通过在Page的Unload事件中注入JavaScript来模拟弹出警告对话框。该方法避免了直接使用ClientScript、Literal或Response.Write的方式,并讨论了使用ScriptManager注册脚本以确保执行顺序的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我們都知道在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的差別。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值