introduction
在web application的表单提交过程中显示“please wait”信息或者是gif动画图片通常是很有用的,特别是提交过程比较久的情况。我最近开发了一个调查提交程序,在程序里内部用户通过一个网页上传excel电子表格。程序将上传的电子表格数据插入到数据库中。这个过程只需要几秒钟,但即便是几秒钟,在网页是看来却是非常明显的等待过程。在程序测试的时候,一些用户重复地点击上传按钮。因此,提供一个视觉的信息来告诉人们上传正在进行中是很有用的。并同时把上传按钮一起隐藏掉,以防止多次点击。这里介绍的控件是button控件的子类,它演示了如何把客户端javascript代码封装在asp.net服务器控件中来提供便利的功能。
虽然外面已经有很多javascript的例子来完成这件事情,但当我试图把这些功能封装到asp.net控件中时我发现了一些问题。我最开始尝试通过javascript的onclick句柄来使button无效,并用另外的文本取代。但我发现很棘手,这样会妨碍到asp.net服务器端的click事件的功能。而最终行得通的,并且对不同浏览器也有很好支持的方法是,让button在div标记中呈现。div可以隐藏并且不妨碍asp.net的click事件。
using the control
作为正常的button控件的派生,pleasewaitbutton的功能与它基本一样。它通过三个附加的属性来管理当按钮被点击后"please wait"信息或图片的显示。
pleasewaittext
这是显示的客户端文本信息,如果存在,当按钮被点击它将取代按钮。
pleasewaitimage
这是显示的图像文件(比如gif动画图像),如果存在,当按钮被点击它将取代按钮。这个属性将变成<img>标记中的src属性。
pleasewaittype
pleasewaittypeenum枚举值之一:textonly,imageonly,textthenimage,或者imagethentext。它控制消息和图片的布局。
下面是一个.aspx文件示例,它演示了一个设置了pleasewaittext和pleasewaitimage的pleastwaitbutton。
<%@ page language="c#" %>
<%@ register tagprefix="cc1" namespace="javascriptcontrols"
assembly="pleasewaitbutton" %>
<script runat="server">
private void pleasewaitbutton1_click(object sender, system.eventargs e)
{
// server-side click event handler;
// simulate something that could take a long time,
// like a file upload or time-consuming server processing
datetime dt = datetime.now.addseconds(5);
while (datetime.now < dt)
{
// do nothing; simulate a 5-second pause
}
// at the end of the loop display a success message
// and hide the submit form
panelsuccess.visible = true;
pleasewaitbutton1.visible = false;
}
</script>
<html>
<head>
<title>testing pleasewaitbutton</title>
</head>
<body>
<form id="form1" method="post" runat="server">
<p>testing the pleasewaitbutton control.</p>
<cc1:pleasewaitbutton id="pleasewaitbutton1" runat="server"
text="click me to start a time-consuming process"
pleasewaittext="please wait "
pleasewaitimage="pleasewait.gif"
onclick="pleasewaitbutton1_click" />
<asp:panel id="panelsuccess" runat="server"
visible="false">
thank you for submitting this form. you are truly
the coolest user i've ever had the pleasure of serving.
no, really, i mean it. there have been others, sure,
but you are really in a class by yourself.
</asp:panel>
</form>
</body>
</html>
how it works
pleasewaitbutton控件在<div>标记中呈现了一个标准的asp.net button。它也呈现了一个空的<div>标记给
信息/图像。在点击按钮时,由javascript函数(见下面的客户端函数)控制按钮的隐藏和信息的显示。为了方便起见,由pleasewaitbutton服务器控件处理所有必需的javascript客户端代码的实施。
由于pleasewaitbutton实施它自己的javascript onclick句柄,所以我们必须采取一些额外的措施来保持原有的onclick句柄,并且允许控件清晰地运行一些客户端验证代码。为了达到此目的,我们首先把button基类还原为一个字符串缓冲,然后巧妙地处理它,把我们定义的onclick代码包含进去。
protected override void render(htmltextwriter output)
{
// output the button's html (with attributes)
// to a dummy htmltextwriter
stringwriter sw = new stringwriter();
htmltextwriter wr = new htmltextwriter(sw);
base.render(wr);
string sbuttonhtml = sw.tostring();
wr.close();
sw.close();
// now modify the code to include an "onclick" handler
// with our pleasewait() function called appropriately
// after any client-side validation.
sbuttonhtml = modifyjavascriptonclick(sbuttonhtml);
// before rendering the button, output an empty <div>
// that will be populated client-side via javascript
// with a "please wait" message"
output.write(string.format("<div id='pleasewaitbuttondiv2_{0}'>",
this.clientid));
output.write("</div>");
// render the button in an encapsulating <div> tag of its own
output.write(string.format("<div id='pleasewaitbuttondiv_{0}'>",
this.clientid));
output.write(sbuttonhtml);
output.write("</div>");
}
这种把button还原成一个字符串缓冲然后处理它的onclick内容的技术是一件很危险的事情(is certainly a hack). 但它可以让我们在父button类中实施标准的验证代码,然后再实现我们的pleasewait() javascript函数调用。如果不这样做,我们只能在验证代码之前就在onclick属性中实施我们的pleasewait()函数调用,除非我们愿意完全重写父button类的属性的呈现。这样就算页面上有输入错误也会产生我们并不希望的按钮隐藏和显示"please wait"信息的效果。因此,我们必须在onclick句柄中强行令我们的客户端pleasewait()函数出现在客户端页面验证之后。
onclick属性的修改发生在modifyjavascriptonclick()函数中。这个函数获取按钮呈现的html字符串,并检查看是否存在onclick属性。如果是,这个函数会检查是否有使用客户端验证代码。如果是这种情况的话,我们定义的pleasewait()函数会加在已经存在的onclick代码的最后面,紧跟在客户端检查的boolin变量page_isvalid后面。这个变量代表是否使用了验证控件。如果page_isvalid的值是false,"please wait"信息将不显示。如果为true则显示。
private string modifyjavascriptonclick(string shtml)
{
// thanks to codeproject member kjellsj (kjell-sverre jerijaervi)
// for code ideas to allow the button to work with client-side validation
string sreturn = "";
string spleasewaitcode = generatepleasewaitjavascript();
// is there an existing onclick attribute?
regex ronclick = new regex("onclick=/"(?<onclick>[^/"]*)");
match monclick = ronclick.match(shtml);
if (monclick.success)
{
// there is an existing onclick attribute;
// add our code to the end of it; if client-side
// validation has been rendered, make sure
// we check to see if the page is valid;
string sexisting = monclick.groups["onclick"].value;
string sreplace = sexisting
+ (sexisting.trim().endswith(";") ? "" : "; ");
if (isvalidatorincludescript() && this.causesvalidation)
{
// include code to check if the page is valid
string scode = "if (page_isvalid) " + spleasewaitcode
+ " return page_isvalid;";
// add our code to the end of the existing onclick code;
sreplace = sreplace + scode;
}
else
{
// don't worry about the page being valid;
sreplace = sreplace + spleasewaitcode;
}
// now substitute our onclick code
sreplace = "onclick=/"" + sreplace;
sreturn = ronclick.replace(shtml, sreplace);
}
else
{
// there isn't an existing onclick attribute;
// add ours
int i = shtml.trim().length - 2;
string sinsert = " onclick=/"" + spleasewaitcode + "/" ";
sreturn = shtml.insert(i, sinsert);
}
return sreturn;
}
这个isvalidatorincludescript() 利用上面的检查来查看是否有使用页面注册的asp.net验证控件的标准javascript代码块。下面则用一个简单的方法测试了是否有验证代码和像page_isvalid的变量存在。
private bool isvalidatorincludescript()
{
// return true if this page has registered javascript
// for client-side validation; this code may not be registered
// if asp.net detects what it thinks (correctly or incorrectly)
// is a down-level browser.
return this.page.isstartupscriptregistered("validatorincludescript");
} 下面这个generatepleasewaitjavascript()构建了包含在onclick属性中的pleasewait() javascript函数。我们可以通过检查控件的属性来决定想要的布局。
private string generatepleasewaitjavascript()
{
// create a javascript "pleasewait()" function call
// suitable for use in an onclick event handler
string smessage = "";
string stext = _pleasewaittext;
string simage = (_pleasewaitimage != string.empty
? string.format(
"<img src=/"{0}/" align=/"absmiddle/" alt=/"{1}/"/>"
, _pleasewaitimage, _pleasewaittext )
: string.empty);
// establish the layout based on pleasewaittype
switch (_pleasewaittype)
{
case pleasewaittypeenum.textthenimage:
smessage = stext + simage;
break;
case pleasewaittypeenum.imagethentext:
smessage = simage + stext;
break;
case pleasewaittypeenum.textonly:
smessage = stext;
break;
case pleasewaittypeenum.imageonly:
smessage = simage;
break;
}
// return the final code chunk
string scode = string.format(
"pleasewait('pleasewaitbuttondiv_{0}',
'pleasewaitbuttondiv2_{1}', '{2}');"
, this.clientid, this.clientid, smessage);
scode = scode.replace("/"", """);
return scode;
}
如果指定了一个pleasewaitimage,就必须包含额外的一段javascript代码来通知客户端预载该图像。这段脚本的注册应该出现在重写的onprerender方法中。注册的键是图像的名称;如果多个按钮都使用同一图像,预载脚本只需要实施一次。这里使用了一个正则表达式来创建javascript图像变量,以保证特殊字字符(比如文件路径中的斜线)转化成下划线。
protected override void onprerender(eventargs e)
{
base.onprerender (e);
// if we're using an image, register some javascript
// for client-side image preloading
if (_pleasewaitimage != string.empty
&& _pleasewaittype != pleasewaittypeenum.textonly)
registerjavascriptpreloadimage(_pleasewaitimage);
}
private void registerjavascriptpreloadimage(string simage)
{
regex rex = new regex("[^a-za-z0-9]");
string simgname = "img_" + rex.replace(simage, "_");
stringbuilder sb = new stringbuilder();
sb.append("<script language='javascript'>");
sb.append("if (document.images) { ");
sb.appendformat("{0} = new image();", simgname);
sb.appendformat("{0}.src = /"{1}/";", simgname, simage);
sb.append(" } ");
sb.append("</script>");
this.page.registerclientscriptblock(simgname + "_preloadscript",
sb.tostring());
}
client-side functions
嵌入的文本文件javascript.txt包含了隐藏按钮的<div>和显示"please wait"信息或图像的客户端代码。这些代码在重写的oninit()方法中调用的私有方法registerjavascriptfromresource()加载。这个方法调用泛型方法getembeddedtextfile() ,在这个泛型方法中把文件做为源加载而把内容返回成字符串。
protected override void oninit(eventargs e)
{
base.oninit(e);
// the client-side javascript code is kept
// in an embedded resource; load the script
// and register it with the page.
registerjavascriptfromresource();
}
private void registerjavascriptfromresource()
{
// load the embedded text file "javascript.txt"
// and register its contents as client-side script
string sscript = getembeddedtextfile("javascript.txt");
this.page.registerclientscriptblock("pleasewaitbuttonscript", sscript);
}
private string getembeddedtextfile(string stextfile)
{
// generic function for retrieving the contents
// of an embedded text file resource as a string
// we'll get the executing assembly, and derive
// the namespace using the first type in the assembly
assembly a = assembly.getexecutingassembly();
string snamespace = a.gettypes()[0].namespace;
// with the assembly and namespace, we'll get the
// embedded resource as a stream
stream s = a.getmanifestresourcestream(
string.format("{0}.{1}", snamespace, stextfile)
);
// read the contents of the stream into a string
streamreader sr = new streamreader(s);
string scontents = sr.readtoend();
sr.close();
s.close();
return scontents;
}
javascript.txt嵌入资源包含了按钮在javascript的onclick句柄中执行的客户端方法pleasewait()。这段代码也调用了一个客户端方法hidediv()以隐藏按钮的容器<div>,然后通过设置innerhtml属性把信息或图像组装进之前空的<div>标记中。辅助函数getdiv()则是通过检查document.getelementbyid, document.all, 和 document.layers用id返回一个<div>对象,保证了不同浏览器的兼容性。下面是javascript.txt的全部代码:
<script language="javascript">
function getdiv(sdiv)
{
var div;
if (document.getelementbyid)
div = document.getelementbyid(sdiv);
else if (document.all)
div = eval("window." + sdiv);
else if (document.layers)
div = document.layers[sdiv];
else
div = null;
return div;
}
function hidediv(sdiv)
{
d = getdiv(sdiv);
if (d)
{
if (document.layers) d.visibility = "hide";
else d.style.visibility = "hidden";
}
}
function pleasewait(sdivbutton, sdivmessage, sinnerhtml)
{
hidediv(sdivbutton);
var d = getdiv(sdivmessage);
if (d) d.innerhtml = sinnerhtml;
}
</script>
原文链接:http://www.codeproject.com/aspnet/pleasewaitbutton.asp
新闻热点
疑难解答
图片精选