Asp. NET Server Control Pleasewaitbutton

Source: Internet
Author: User
Tags format empty file upload implement tostring trim valid visibility
Asp.net| Server | control

Introduction

It is often useful to display "Please wait" information in a Web application form submission, or an animated GIF picture, especially if the submission process is a long one. I recently developed a survey submission program in which internal users upload Excel spreadsheets through a Web page. The program inserts the uploaded spreadsheet data into the database. The process takes only a few seconds, but even in a few seconds, the page seems to be a very obvious waiting process. At the time of the program test, some users repeatedly click the Upload button. Therefore, it is useful to provide a visual information to tell people that uploads are in progress. And also hide the upload button together to prevent multiple clicks. The control described here is a subclass of the button control, which demonstrates how to encapsulate client-side JavaScript code in a ASP.net server control to provide convenience functionality.

Although there are a lot of javascript examples out there to do this, I find some problems when I try to encapsulate these features into the ASP.net control. I first tried to invalidate the button with JavaScript's onclick handle and replace it with another text. But I found it tricky, which would hinder the ASP.net server-side click event. And the way to make it work, and to have a good support for different browsers, is to have the button present in the div tag. The div can be hidden and does not interfere with the ASP.net click event.

Using the control

As a derivation of the normal button control, the Pleasewaitbutton function is essentially the same as it is. It manages the display of "Please wait" information or a picture after the button is clicked through three additional properties.

Pleasewaittext
This is the display of the client text information, if present, when the button is clicked it will replace the button.
Pleasewaitimage
This is the display of image files (such as GIF animated images), if present, when the button is clicked it will replace the button. This property will become the SRC attribute in the tag.
Pleasewaittype
One of the Pleasewaittypeenum enumeration values: Textonly,imageonly,textthenimage, or Imagethentext. It controls the layout of messages and pictures.

The following is an example of an. aspx file that demonstrates a Pleastwaitbutton that sets the Pleasewaittext and Pleasewaitimage.

<%@ 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)
{
Doing 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>

<title>testing pleasewaitbutton</title>
<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"
/>

<asp:panel id= "panelsuccess" runat= "Server"
Visible= "false" >
Thank for the 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>


How It Works

The Pleasewaitbutton control presents a standard asp.net Button in the <div> tag. It also presents an empty <div> mark to
Information/images. When the button is clicked, the JavaScript function (see client function below) controls the hiding of the button and the display of the information. For convenience, the Pleasewaitbutton server control handles the implementation of all the required JavaScript client code.
Since Pleasewaitbutton implements its own JavaScript onclick handle, we must take some extra steps to maintain the original onclick handle and allow the control to run some client-side validation code clearly. To do this, we first revert the button base class to a string buffer and then handle it subtly, including our defined onclick code.


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 ();
Url 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'll 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 a encapsulating <div> tag of its own
Output. Write (String. Format ("<div id= ' pleasewaitbuttondiv_{0} ' >",
This. ClientID));
Output. Write (sbuttonhtml);
Output. Write ("</div>");
}
The technique of restoring a button to a string buffer and then processing its onclick content is a dangerous thing (is certainly a hack). But it allows us to implement standard validation code in the parent button class, and then implement our pleasewait () JavaScript function call. If we do not, we can only implement our pleasewait () function call in the onclick attribute before validating the code unless we are willing to completely override the rendering of the attributes of the parent button class. This way, even if there is an input error on the page, it will result in buttons that we don't want to hide and display the "Please Wait" message. Therefore, we must force our client pleasewait () function to appear in the onclick handle after the client page validation.
The modification of the OnClick property occurs in the Modifyjavascriptonclick () function. This function gets the HTML string rendered by the button and checks to see if the OnClick property exists. If so, this function checks to see if there is any use of client-side validation code. If this is the case, our defined pleasewait () function is appended to the last side of the existing onclick code, immediately following the Boolin variable page_isvalid that the client checks. This variable represents whether the validation control is used. If the value of Page_isvalid is false, the "Please wait" information will not be displayed. If true, displays the.
private string Modifyjavascriptonclick (String sHtml)
{
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 the 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;

}

This isvalidatorincludescript () uses the above check to see if there are standard JavaScript blocks for asp.net validation controls that use page registrations. The following is a simple way to test whether there are validation code and variables like Page_isvalid.
private bool Isvalidatorincludescript ()
{
Return TRUE If this page has registered JavaScript
for client-side validation; This code may is registered
If ASP.net detects what it thinks (correctly or incorrectly)
is a Down-level browser.

return this. Page.isstartupscriptregistered ("Validatorincludescript");
The following generatepleasewaitjavascript () constructs the pleasewait () JavaScript function contained in the OnClick property. We can determine the layout we want by checking the properties of the control.
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 (
", _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;
}
If you specify a pleasewaitimage, you must include an additional piece of JavaScript code to notify the client to preload the image. The registration of this script should appear in the overridden OnPreRender method. The registered key is the name of the image, and if multiple buttons use the same image, the preload script needs to be implemented only once. A regular expression is used here to create a JavaScript image variable to ensure that special character characters, such as diagonal lines in the file path, are converted to underscores.

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

The embedded text file Javascript.txt contains the <div> of the hidden button and the client code that displays "Please wait" information or images. The code is loaded in the private method Registerjavascriptfromresource () that is invoked in the overridden OnInit () method. This method invokes the generic method Getembeddedtextfile (), in which the file is loaded as a source and the content is returned as a string.


protected override void OnInit (EventArgs e)
{
Base. OnInit (e);

The client-side JavaScript code is kept
In a 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 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;
}
The Javascript.txt Embedded Resource contains the client method Pleasewait () that the button executes in the JavaScript onclick handle. This code also calls a client method Hidediv () To hide the button's container <div>, and then assembles the information or image into the previously empty <div> tag by setting the innerHTML property. The auxiliary function Getdiv () is to check document.getElementById, document.all, and Document.layers to return a <div> object with ID to ensure compatibility of different browsers. Here is the full code for 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>

Original link: http://www.codeproject.com/aspnet/PleaseWaitButton.asp



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.