A templated PleaseWait Button, introduction to template Control

1.Introduction

This article presents the construction of a templated ASP.NET control, working as a PleaseWait button. Using C# with Asp.Net 2.0, you will see how to create a templated control and add specific fonctionnality.

Some times, you need to perform some long task during a click button event, when submiting your page. Some times, the form's validation can request some call to database, or remoted call, web services ... To inform the user that the server is doing something long, it's a good idea to display a waiting message.

I've seen some articles that re-create a button with an added properties, that display a message. But the presentation never suits to me. So I decided to create a complete one, customizable with a template fonctionnality.

2.The result to optain

What I want to have, is something like this in my asp.net page :

<Test:PleaseWaitButton ID="PWB" runat="server">
<PleaseWaitMessageTemplate>
<div style="width:500px;color:green;border:1px solid red;text-align:center">
<div>Please wait a moment, </div>
<div>we are checking your informations ...</div>
<asp:Image runat="server" ImageUrl="wait.gif" />
</div>
</PleaseWaitMessageTemplate>
</Test:PleaseWaitButton>

Then we have the button, and the place to define the graphic visualisation of the please wait message.

To look like a real button, we need to define a event hanndler on the button click. We want to be able to customize the text of the button, with the Text property too.

In a form, usually we want to use ap.net validation. Then the button need to check this validation and define if needed a ValidationGroup property.

<Test:PleaseWaitButton ID="PWB" runat="server" OnClick="ClickButton" ValidationGroup="myGroup" Text="Please Click">
<PleaseWaitMessageTemplate>
<div style="width:500px;color:green;border:1px solid red;text-align:center">
<div>Please wait a moment, </div>
<div>we are checking your informations ...</div>
<asp:Image runat="server" ImageUrl="wait.gif" />
</div>
</PleaseWaitMessageTemplate>
</Test:PleaseWaitButton>

3.Creating the template button

First, you have to inherits from Control and implement INamingContainer. You have to define the ParseChildren(true) attribute too.

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
[ParseChildren(true)]
[DefaultProperty("Text")]
public class PleaseWaitButton : Control, INamingContainer
{
}

4.1.The ITemplate property

This is all you need : Having a template propety. PersistenceMode is used to tell the parser that property persist as inner property. TemplateContainer is unused here, it's for databind typing.

private ITemplate _pleaseWaitMessageTemplate = null;
[Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(TemplateItem))]
public ITemplate PleaseWaitMessageTemplate
{
get { return _pleaseWaitMessageTemplate; }
set { _pleaseWaitMessageTemplate = value; }
}

We need to define a TemplateItemp class too.

// TemplateItem should implement INamingContainer
[ToolboxItem(false)]
public class TemplateItem : Control, INamingContainer
{
}

4.2.Creation of the controls

We'll override the CreateChildControls method to create a Panel that will contains our control. In this Panel, if the user defines a template, we instanciate it (as a TemplateItem). If no template is defined, we create a default LiteralControl with a default message.

And just after, we add a button, with a click handler defined and with Text property set to our Text property.

With Css style, we set the Panel to display none. The button, outside the panel, is always visible.

Collapse
protected override void CreateChildControls()
{
Controls.Clear();
// Create an hidden panel
Panel panelMessage = new Panel();
panelMessage.Attributes["style"] = "display:none";
if (PleaseWaitMessageTemplate != null)
{
// if a template is defined, use it
TemplateItem templateItem = new TemplateItem();
PleaseWaitMessageTemplate.InstantiateIn(templateItem);
panelMessage.Controls.Add(templateItem);
}
else
{
// else, create a default ugly message
panelMessage.Controls.Add(new LiteralControl("Plesae Wait ..."));
}
// Button is created with Text property
// and a click handler
Button boutonValidation = new Button();
boutonValidation.Text = Text;
boutonValidation.Click += b_Click;
// Then add panel and button
Controls.Add(panelMessage);
Controls.Add(boutonValidation);
}

4.3.Creation of the Properties

As seen, we need to hold a ValidationGroup property and a Text property.

If no text is defined, we use the default "OK" value.

We define a click event too.

To ensure control creation, let's override the Controls property and call EnsureChildControls() (that will call CreateChildControls if needed)

[Bindable(true), Category("Behavior"), Description("Validation group")]
public string ValidationGroup
{
get { return (string)ViewState["ValidationGroup"] ?? string.Empty; }
set { ViewState["ValidationGroup"] = value; }
}
[Bindable(true), Category("Appearance"), DefaultValue("OK"), Description("Button's text")]
public string Text
{
get { return (string)ViewState["Text"] ?? "OK"; }
set { ViewState["Text"] = value; }
}
private event EventHandler _clickHandler;
public event EventHandler Click
{
add { _clickHandler += value; }
remove { _clickHandler -= value; }
}
public override ControlCollection Controls
{
get { EnsureChildControls(); return base.Controls; }
}

4.4.Validation

We have to ask for the validation of the page (with Page.Validate method). If a ValidationGroup is defined, we ask for validation of this group.

private void b_Click(object sender, EventArgs e)
{
// manual validation
if (!string.IsNullOrEmpty(ValidationGroup))
Page.Validate(ValidationGroup);
else
Page.Validate();
// Fire the user-define click event, if defined
if (_clickHandler != null)
_clickHandler(sender, e);
}

4.4.Client-side javascript

On the client-side, we have to do 2 things :

- Client validation

- And display/hide the please wait message

This is done with javascript, we will play with the display style of the panel (represented as a div html), if validation is OK or NOK.

So let's add some javascript in the rendering phase, to call a specific javascript function on the clientClick button event (see comments).

But first, we have to find the clientId of the Panel.

protected override void OnPreRender(EventArgs e)
{
// we look for the panel and set an ID
// warning : this operation can't be done in CreateChildControls, it would have been too earl
Panel panelMessage = null;
foreach (Control control in Controls)
{
if (control is Panel)
{
control.ID = ID + "_waiting";
panelMessage = (Panel) control;
}
}
// When panel founded, look for the button, and add a clientside function 
//(with panel clientId as parameters)
if (panelMessage != null)
{
foreach (Control control in Controls)
{
if (control is Button)
{
((Button) control).OnClientClick =
string.Format("checkForm('{0}')", panelMessage.ClientID);
}
}
}
base.OnPreRender(e);
}

On render, create the javascript functions that will manage the display, depending on the result of the client validation (client validation is done with Page_ClientValidate method)

Collapse
protected override void Render(HtmlTextWriter writer)
{
// script client-side creation :
// If there's a validation group, call validation function with the group as parameters
// else without parameters
string validationGroupParameters = string.IsNullOrEmpty(ValidationGroup) ?
string.Empty : string.Format("'{0}'", ValidationGroup);
// if validation is OK, display panel (and waiting message)
// if validation NOK, hide panel and return false
string script = @"function getObj(id)
{
var o;
if (document.getElementById)
{
o = document.getElementById(id).style;
}
else if (document.layers)
{
o = document.layers[id];
}
else if (document.all)
{
o = document.all[id].style;
}
return o;
}
function setDisplay(id)
{
var o = getObj(id);
if (o)
{
o.display = 'block';
}
}
function unsetDisplay(id)
{
var o = getObj(id);
if (o)
{
o.display = 'none';
}
}
function checkForm(divWaiting)
{
try
{
if (!Page_ClientValidate(" + validationGroupParameters + @"))
{
unsetDisplay(divWaiting);
return false;
}
}
catch (e) {}
setDisplay(divWaiting);
}";
Page.ClientScript.RegisterStartupScript(GetType(), "javascriptButton", script, true);
base.Render(writer);
}

4.Create a default page that use this button :

4.1.With no validation

Just define the template control, and the template property. Add if needed a click button handler

<Test:PleaseWaitButton ID="PWB" runat="server" OnClick="ClickButton">
<PleaseWaitMessageTemplate>
<div style="width:500px;color:green;border:1px solid red;text-align:center">
<div>Please wait a moment, </div>
<div>we are checking your informations ...</div>
<asp:Image runat="server" ImageUrl="wait.gif" />
</div>
</PleaseWaitMessageTemplate>
</Test:PleaseWaitButton>

In code behind, simulate the long task to perform ...

protected void ClickButton(object sender, EventArgs e)
{
Thread.Sleep(2000);
}

4.2.With validation

4.2.1.Without validation group

Let's define a textBox and add a client side validation with a RequiredFieldValidator control and a server side validation with a CustomValidator control.

<asp:TextBox runat="server" ID="aTextBox" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="aTextBox"
ErrorMessage="Field should have a value" Display="dynamic"/>
<asp:CustomValidator runat="server" OnServerValidate="ValidateFunction"
Display="dynamic" ErrorMessage="Value should be ABC" />
protected void ClickButton(object sender, EventArgs e)
{
if (Page.IsValid)
{
Thread.Sleep(2000);
Response.Write("<br/>Informations are OK<br/>");
}
}
protected void ValidateFunction(object source, ServerValidateEventArgs args)
{
args.IsValid = aTextBox.Text == "ABC";
}

4.2.2.With validation group

You can try with a validation group too, like this :

Collapse
<asp:TextBox runat="server" ID="aTextBox" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="aTextBox"
ErrorMessage="Field should have a value" Display="dynamic" ValidationGroup="myGroup"/>
<asp:CustomValidator runat="server" OnServerValidate="ValidateFunction"
Display="dynamic" ErrorMessage="Value should be ABC" ValidationGroup="myGroup"/>
<Test:PleaseWaitButton ID="PWB" runat="server" OnClick="ClickButton" ValidationGroup="myGroup">
<PleaseWaitMessageTemplate>
<div style="width:500px;color:green;border:1px solid red;text-align:center">
<div>Please wait a moment, </div>
<div>we are checking your informations ...</div>
<asp:Image runat="server" ImageUrl="wait.gif" />
</div>
</PleaseWaitMessageTemplate>
</Test:PleaseWaitButton>
protected void ClickButton(object sender, EventArgs e)
{
if (Page.IsValid)
{
Thread.Sleep(2000);
Response.Write("<br/>Informations are OK<br/>");
}
}
protected void ValidateFunction(object source, ServerValidateEventArgs args)
{
args.IsValid = aTextBox.Text == "ABC";
}

5.Preview

6.Conclusion

I hope you'll find this template button usefull and have maybe learn how to create a template control in asp.net with C#.

Validation is a critical point and very usefull method in asp.net page. Knowing how to take advantage of validation with the validation API can be very powerfull too.

If you see an error in this article, in the source code or for any other information, let me a comment.

posted @ 2008-08-11 08:57  广陵散仙(www.cnblogs.com/junzhongxu/)  阅读(431)  评论(0编辑  收藏  举报