ASP.NET中像使用MessageBox一样执行JS的消息框脚本
翻看多年前的例子,发现了这样的一个小类,能够让ASP.NET服务器端代码像WinForm的MessageBox.Show一样快速的弹出消息框。具体的实现还是用JS实现的,而且并非我原创,只是年代久远,已经记不起从哪里找到的了。现在的解决方案很多,Ajax的效果都有了,这个就写下来留念一下吧。主要原理还是使用ClientScriptManager的RegisterStartupScript方法实现。不罗嗦,上代码。
查看代码
1 /// <summary> 2 /// 在Web中模仿MessageBox的消息框 3 /// </summary> 4 public static class ShowMessage 5 { 6 /// <summary> 7 /// 显示警告框的客户端脚本 8 /// </summary> 9 /// <param name="objPage">需要显示警告框的页面,一般用this调用</param> 10 /// <param name="message">提示的内容</param> 11 public static void Alert(Page objPage, string message) 12 { 13 string key = "Alert"; 14 string script = string.Format("alert('{0}');", message); 15 objPage.ClientScript.RegisterStartupScript(objPage.GetType(), key, script, true); 16 } 17 18 /// <summary> 19 /// 显示警告框后,跳转地址 20 /// </summary> 21 /// <param name="objPage">需要显示警告框的页面,一般用this调用</param> 22 /// <param name="message">提示的内容</param> 23 /// <param name="url">提示后跳转的URL</param> 24 public static void Alert(Page objPage, string message, string url) 25 { 26 string key = "Alert"; 27 string script = String.Format("alert('{0}');window.location='{1}';", message, url); 28 objPage.ClientScript.RegisterStartupScript(objPage.GetType(), key, script, true); 29 } 30 }
服务器端调用的代码
ShowMessage.Alert(this, "提示信息"); ShowMessage.Alert(this, "提示信息","跳转页面.aspx");
Boniz·Lee


浙公网安备 33010602011771号