관리 메뉴

심재운 블로그

ASP.NET 3.5 용 Buttons, Message Box and Confirm Box 만들어 보기 본문

닷넷관련/ASP.NET WEBFORM

ASP.NET 3.5 용 Buttons, Message Box and Confirm Box 만들어 보기

재우니 2009. 10. 27. 02:31







Buttons, Message Box and Confirm Box in ASP.NET 3.5

Table Of Contents

Introduction

In this article I will introduce the library containing confirm box, message box and new buttons for easy coordination between them. There are some articles about the similar topic but either one of them doesn't cover too many scenarios of using confirm box and message box as this article. This article provides you a detailed description of the ASP.NET controls as well as the list of examples.

Features of this library:

  • Everything is located inside one DLL even CSS files and JS scripts which means easy deploy.
  • No relation to 3th party libraries. No relation even to AJAX Control Toolkit.
  • Java Script and CSS files loaded automatically.
  • Some parts of the library are prepared for customization.

Deploy and Use

This library is designed for fast deploy and easy use. There is only one library you need to deploy. No CSS files, no ASCX files, no JavaScript files. Everything is handled automatically. For examples look at the chapter containing demos, choose your scenario, see the demo, see the code to use it and use it. If you are interested how it works, read the whole article.

Microsoft AJAX JavaScript Library required

The examples in this article require the Microsoft AJAX JavaScript Library to be loaded. For you it means to add ScriptManager control into a page. Nothing more.

Buttons

This article is primary about message box and confirm box. But I had created the new type of buttons as well. I will discuss the buttons first and then I explain the popup boxes. The buttons and the boxes mentioned in this article are kind of connected in order to be used in a simple way. But remember that they are independent. In case you will not like my buttons, you can just use the popup boxes. Let's look at the class diagram of the Buttons:

Picture  1 - Class Diagram of Buttons

Picture 1 - Class Diagram of Buttons

As you can see on the picture 1 there is the ButtonBase class and n of the concrete buttons. The idea of these buttons is that button is a simple DIV element. This is giving you a freedom of designing buttons. If you are good at CSS and design then imagine what you can do with the simple DIV. And this DIV you can declare as a button. Basically you are not restricted to input tag with type of button or also known ASP.NET ImageButton or stuff like that. All you need to do is to create your own class, derive from ButtonBase and specify the content of the button. The ButtonBase class contains all the functionality around the ASP.NET buttons. You can imagine that the ButtonBase is the DIV container and you can put everything (Control) into this container and what you put into it will be a ASP.NET button. If you noticed, there is the generic T argument which have to be specified in the concrete implementation of the button. And this T argument is the content of the DIV.

Note: If you are familiar with the HTML and CSS then you can propose that the DIV is not an appropriate to be a button due to its behavior in HTML formatting. So that's the reason why ButtonBase class always wrap it into a table with zero cell spacing and zero margin and padding.

In the library there are already created some of the concrete implementations of the button. The table below listed the currently available buttons:

Name Description
TextButton DIV with text element inside.
ClassicButtons The input tag with type of button inside the DIV.
ImageButton Image inside the DIV.
LinkButton HTML Link inside the DIV.

Now it's time to first demo. Here is the link: Demo 1. Please be patient, there is nothing impressive in the first demo. There are just an examples of the listed buttons. I guess much interesting will be the demo 2.

Back to demo 1 as you see the code is simple. For example for TextButton it is:

Collapse
<dns:TextButton runat="server" ID="cmdButtA" Text="Button A" OnClick="Click_ButtonA" PredefinedStyle="Red" />
Note: I completely ignored the submit behavior of the HTML forms and every postback is send via javascript (maybe you know __doPostBack and __doPostBackWithOptions functions). I know, that can be kind of rude but to be honest I don't need the submit behavior. I don't need two approaches to send the form to the server. What if javascript is not allowed in a browser? Well, this topic is about AJAX and I need to have more available than the javascript and if at least the javascript is not available then sorry.

Is there another benefit of these buttons?

Yes, there is. It's the property ConfirmText. If you set it to the text then this text will displayed in a confirm box before the postback will be send. The example can looks like this:

Collapse
<dns:TextButton runat="server" ID="cmdButtA" Text="Button A" OnClick="Click_ButtonA" PredefinedStyle="Red" ConfirmText="Do you want to really send a postback?"  />

Let's see the screen-shot.

Picture2 - Screen-shot of the confirm box

If you want to try it, I recommend you to browse Demo 2 here which is basically the Demo 1 but the buttons have set the property ConfirmText.

Now I will explain how to create a custom button with a custom content and afterwards I will explain where the confirm box in Demo 2 come from.

Creating a custom button

I will introduce it in the steps to create an ImageButton.

Create a class:

Collapse
public class ImageButton {

}

Derive from ButtonBase and specify the content:

Collapse
public class ImageButton : ButtonBase<Image> {

}

Because I'm creating the button with an image as content then I specify an Image as generic parameter.

Override and implement CreateContentControl method:

Collapse
protected override Image CreateContentControl() {
return new Image();
}

CreateContentControl method is called in OnInit and a new control returned by this method is added to the page life cycle before the base.OnInit is called which means the OnInit itself will be called on your content control.

Note: after Init phase of page life cycle you will have your content control available in ContentControl property.

Add custom properties to you control:

Is it obvious that the ImageButton will need something like an ImageUrl to specify the URL of the image. So let's add it:

Collapse
public string ImageUrl {
get {
string str = (string)this.ViewState["ImageUrl"];
if (str != null) {
return str;
}
return string.Empty;
}
set {
this.ViewState["ImageUrl"] = value;
}
}

Override the OnPreRender to do your final changes on your control:

In OnPreRender is the right time to set final changes to the content control. Let's set ImageUrl to the real image and Text property to the AlternateText on real image like the following:

Collapse
protected override void OnPreRender(EventArgs e) {

ContentControl.ImageUrl = ImageUrl;
ContentControl.AlternateText = Text;

base.OnPreRender(e);
}

The whole source code is available in download.

Confirm Box and Message Box

Let me introduce the class diagram first.

Picture 3 - The class diagram of Confirm Box and Message Box

Picture 3 - The class diagram of Confirm Box and Message Box

As you can see on the diagram there is the class called BoxContextPage. For what exactly is the BoxContextPage taking care of? It is taking care of: one instance of the confirm box, one instance of the message box, the configuration of boxes, the localization of buttons located in the boxes and the loading of CSS resources. To derive from this type of page is the easiest way to add the boxes into your page. For example the code behind of the Demo 2 page looks like this:

Collapse
public partial class Default : BoxContextPage {

protected void Page_Load(object sender, EventArgs e) {
}

protected void Click_ButtonA(object sender, object args) {
lblResult.Text = "You clicked on button A";
}

protected void Click_Cat(object sender, object args) {
lblResult.Text = "You clicked on a cat with glasses";
}

protected void Click_Classic(object sender, object args) {
lblResult.Text = "You clicked on a classic button.";
}

protected void Click_LinkButton(object sender, object args) {
lblResult.Text = "You clicked on a LinkButton.";
}

}

You see? Just derive from BoxContextPage instead of System.Web.UI.Page and all functionality about the boxes will be available in you page.

From the precedent class diagram you can assume that there will be only one instance of the message box and one instance of the confirm box for the page. It's because there is no reason to have more instances of that on the page because only one popup box can be displayed the moment. Thus only one HTML code of confirm box and message box is downloaded to the client. Plus the popup boxes are client driven both the message displayed in the box and the icon in the box. For visual representation look at the following picture:

Picture 4

Picture 4

The BoxContextPage life-cycle

I'm pretty sure you have heard about ASP.NET page life cycle. If you don't, please look at the reference [4] listed in the references at the end of this article. I injected two stages of the page life cycle in order to create instances of the controls and in order to localize it. For visual explanation look at the following activity diagram:

Picture 5 - The BoxContextPage life-cycle

Picture 5 - The BoxContextPage life-cycle

ASP.NET AJAX controls in this project

There are four ASP.NET AXAJ controls in this project. They are basically the ASP.NET controls extended of JavaScript class and some of them has related CSS files. For visual presentation you can look at the following picture:

Picture 6

Picture 6

Well, everything you can see in the precedent picture is located in one library which means very easy deploy.

The PopupBackgroud control

The PopupBackground control is responsible for covering whole page by the shadow when one of the popup boxes is displayed. It's automatically used by MessageBox and ConfirmBox.

The configuration control

As I mentioned the popup boxes are server and client side driven. Especially the message box is usually required to be server and client side driven. The Configuration control is providing the URLs to the icons on the server side as well as on the client side. The advantage of having Configuration control is ability to override this class and specify a custom icons. Let's look at the steps how to do that.

Custom icons in message box and confirm box

  • Draw (or buy or find on the internet) your icons: question, info, warning and error. 16x16 pixels.
  • Create your configuration class. Derive from Configuration and override the following properties to specify the new paths to your new icons:
    • QuestionIcon
    • InfoIcon
    • WarningIcon
    • ErrorIcon
    The class can look like this:
    Collapse
    public class MyConfiguration : Configuration {

    public override string QuestionIcon {
    get {
    return "question.png";
    }
    }

    public override string InfoIcon {
    get {
    return "info.png";
    }
    }

    public override string WarningIcon {
    get {
    return "warning.png";
    }
    }

    public override string ErrorIcon {
    get {
    return "error.png";
    }
    }
    }
  • In your page override CreateConfiguration method. And return the instance of your new Configuration class. This can be reached by to following code:
    Collapse
    public partial class Default : BoxContextPage {

    protected override Configuration CreateConfiguration() {
    return new MyConfiguration();
    }
    }

So and that's it. At last comes the chapters how to handle message box and confirm box directly.

Server Side Driven Message Box

There is the MessageBox variable available directly in your page and you can call Show method on it. Here is the code:

Collapse
protected void Click_cmdButt(object sender, object args) {
// do your action... database operation or whatsoever

MessageBox.Show("Your operation was successfully completed.",
DotNetSources.Web.UI.Buttons.Popup.Icon.Info);
}

The Demo 3 is prepared here.

Tip to access Message Box from a Custom Control

If you are developing a custom control such an User Control or a Web Control, you can access the message box this way:

Collapse
Helper.RetypeToBoxContextPage(Page).MessageBox.Show(
"Your operation was successfully completed.",
DotNetSources.Web.UI.Buttons.Popup.Icon.Info);

The method RetypeToBoxContextPage is already responsible for throwing an Exception if your page is not derived from the BoxContextPage.

Server Side Driven Confirm Box

This scenario is not supported by this library. Why? Because it's not usual. It's usual for message box because in case of message box you are about to inform what happened on the server. In case of confirm box you are asking a simple question (if user wants to send a postback) and you probably don't need to involve the server interaction. So that's the reason I do not support this scenario.

Class diagram of JavaScript classes

Before I show you how to handle confirm box and message box from the client, I introduce the class diagram of JavaScript classes. Here it is:

Picture 7 - class diagram of JavaScript classes

Picture 7 - class diagram of JavaScript classes

Client Side Driven Message Box

This scenario is little bit unusual, however this library is prepared for it. From the class diagram of JavaScript classes you can see there is the static method named get_Instance on the MessageBox class. So, you can display the message box from JavaScript like this:

Collapse
DotNetSources.MessageBox.get_instance().Show('This message box was displayed from JavaScript!', DotNetSources.Icons.Info)

This is the demo 4 and you can try it here.

Client Side Driven Confirm Box

This scenario is useful when you don't want to use my buttons from this library. The situation is very similar as client side driven message box. From the class diagram of JavaScript classes you can assume there is the static get_instance method for getting instance of ConfirmBox and Show method to display it. However the parameters for Show method are different. Especially the second parameter is not the type of icon but the client ID of the button you want to fire when user click to YES. Take a note it is a client ID of the control. I mean the ID which is rendered to HTML. The example to use client side driven confirm box:

Collapse
<asp:Button runat="server" ID="cmdSubmit" Text="This is a simple ASP.NET button with confirmation"
OnClick="Click_Submit"
OnClientClick="javascript: DotNetSources.ConfirmBox.get_instance().Show('This message box was displayed from JavaScript!',
'ctl00$contentExample$cmdSubmit'); return false;"
/>

Look at the Demo 6 here.

Availability of JavaScript classes

If you are not so familiar with MS AJAX JavaScript library, this chapter helps you better understand when the object like MessageBox will be prepared to use. All application objects are created in load phase of the ASP.NET AJAX Client Life-Cycle. See the resource [5] for more information about it. So the first safe time when you can call it is in pageLoad function. See the demo here..

Localization

Sometimes you want to have texts in buttons localized to your language. No problem. There are three properties on BoxContentPage prepared for it:

  • MessageBoxButtonText
  • PositiveButtonText
  • NegativeButtonText

And if you remember the BoxContextPage life-cycle, it must be set before PreRender phase of page life-cycle. See the demo 7 here.

Examples with Repeater and DataGrid

The most common situation of using confirm box is in Repeater or DataGrid. Imagine you have a table with records and the button to delete the record from the table. Usually you want to ask the user if he/she really wants to delete an item. The buttons are prepared for it and you can see how it works on the following demos:

Repeater demo: here

DataGrid demo: here

Does it work in partial rendering?

Yes it does and I have prepared the last demo about it. Demo is here.

License about the icons

Well, everything in this article is made by me exclude the icons in popup boxes. Unfortunately I'm not the graphic so I found the icons on the internet. The icons are drawn by Bruno Maia, IconTexto and they are for free for non commercial use, for more information please read the license here. If you want to get rid of default icons and use your own icons, read this chapter.

Sources also on Codeplex.com

The sources are available also on the http://popupboxes.codeplex.com/ I'm talking about it because there is the issue tracker. This library is tested, however if find a bug, please report it to the issue tracker. Thank you.

Conclusion

I hope you liked my article and I hope it was useful. I'd like to invite you to the message board below this article. I will try to answer all of your questions. I will be also very glad if you will vote. Thank you very much for reading.

List of Demos

  • Demo 1
    Description: Click --> postback
    Link: here
  • Demo 2
    Description: Click --> Confirm Box --> postback
    Link: here
  • Demo 3
    Description: Click --> postback --> display message box
    Link: here
  • Demo 4
    Description: Click --> javascript call to display message box
    Link: here
  • Demo 5
    Description: Displaying message box when the page is loaded
    Link: here
  • Demo 6
    Description: Client side driven confirm box on a simple ASP.NET button
    Link: here
  • Demo 7
    Description: Localization of buttons
    Link: here
  • Demo 8
    Description: Repeater
    Link: here
  • Demo 9
    Description: DataGrid
    Link: here
  • Demo 10
    Description: Partial rendering
    Link: here

References


0 Comments
댓글쓰기 폼