您的位置:首页 > 其它

一个小函数:在Page和UpdatePanel都能显示信息的Alert

2007-09-03 10:46 253 查看
如果平时我们要在Page中显示一个提示信息,通常会采用类似下面的方式:

Page.ClientScript.RegisterClientScriptBlock(typeof(this), "key1", "<script type=\"text/javascript\">window.alert(\"test\");</script>", true);
可是如果这段代码,放到一个包含UpdatePanel的页面,就有可能出现问题,因为UpdatePanel已经对http的输入输出作了处理,不允许手动向网页中额外添加内容,通常这个时候会给出一个异常。微软曾经给出一个清单,上面是和UpdatePanel不兼容的ASP.NET服务器控件列表,有很多也都是因为这个原因。但是同时微软也给出了另外一个函数,用于解决这个问题,就是ScriptManager.RegisterClientScriptBlock(),采用这个方法注册的javascript脚本和UpdatePanel就没有冲突了。

所以总结两种情况,写了下面的小函数:

public class WebMessageBox
{
public static void Show(string infomation, Control control)
{
if (StringHelper.IsNullOrEmpty(infomation))
{
throw new ArgumentException("没有设置要显示的信息");
}

bool isPage = (control is Page);
bool isUpdatePanel = (control is UpdatePanel);

if (!isPage && !isUpdatePanel)
{
throw new ArgumentException("信息只能输出到Page或者UpdatePanel中");
}

bool addScriptTags = true;
string script = string.Format("window.alert('{0}');", infomation);
string key = string.Format("WebMessageBox{0}", DateTime.Now.ToString());
Type registerType = typeof(WebMessageBox);

if (isPage)
{
Page page = control as Page;
page.ClientScript.RegisterClientScriptBlock(registerType, key, script, addScriptTags);
}

if (isUpdatePanel)
{
UpdatePanel updatePanel = control as UpdatePanel;
ScriptManager.RegisterClientScriptBlock(updatePanel, registerType, key, script, addScriptTags);
}
}
}
说明:
只要是在网页中提示信息这种情况,都可以直接调用这个函数,第二个参数注意一下就可以。
这不是一个完整的代码,有一个StringHelper.IsNullOrEmpty()是我自己写的代替string.IsNullOrEmpty的方法没有放上来。
script key的生成比较偷懒,不影响大局就没有修改。
之前想过把另外两种提示框(confirm和prompt)也放上来,后来发现逻辑上就不成立,实现不了类似Winform的那种效果,If(WebMessageBox.Show("input name", WebMessageBoxType.Prompt" == "admin") {},暂时作罢,以后可能会通过自定一个窗口实现这种效果。
只是一段小代码,没什么技术含量可言。。。^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐