Thursday, January 17, 2008

Using AjaxControlToolkit ModalPopup Control to Show Alert Dialog Instead of Javascript "alert" Popup Box

Almost in all our web applications we use modal information dialogs. Most often we use javascript "alert" function but it has some shortcomings:

1) It appears differently in different browsers

2) It can not display rich formatted text

3) It can not contain html elements, such as buttons, textboxes.

4) It can not change background, as we see AjaxControlToolkit's ModalPopup control can

Its rather simple to show well formatted, nice modal popup.

It looks like:

image

You can see completed example online, or download source code.

 

The ModalPopup control itself is well documented control. You can see how to set its properties here.

The only different approach I use here is: I am showing popup from javascript function, rather then setting the behavior in markup.

I am setting the TargetControlID property of popup extender to some hidden button on the page.

Then I created the following script:

/// --------------------------------------------------
/// mainScreen object
/// --------------------------------------------------
var mainScreen =
{
    mainModalExtender : null,           // modalExtender object on main page
    mainModalTitleSpan : null,          // title span object
    mainModalContentsDiv : null         // div inside modal dialog
}

mainScreen.Init = function() {
    /// <summary>
    /// Initializes mainScreen variables
    /// </summary>
    this.mainModalExtender = $find('mbMain');
    this.mainModalTitleSpan = $get("spanTitle");
    this.mainModalContentsDiv = $get("mainModalContents");
};
mainScreen.ShowModal = function(_title, _html) {
    /// <summary>
    /// Shows modal dialog with contents equal to _html
    /// </summary>
    /// <param name="_title">Title of modal popup</param>
    /// <param name="_html">HTML that should be shown inside popup</param>
    this.mainModalTitleSpan.innerHTML = _title;
    this.mainModalContentsDiv.innerHTML = _html;
    this.mainModalExtender.show();
};
mainScreen.CancelModal = function() {
    /// <summary>
    /// Hides modal dialog 
    /// </summary>
    this.mainModalExtender.hide();
};


/// --------------------------------------------------
/// Page events processing
/// --------------------------------------------------

Sys.Application.add_load(
    applicationLoadHandler
    );
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
    endRequestHandler
    );
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
    beginRequestHandler
    );

function applicationLoadHandler() {
    /// <summary>
    /// Raised after all scripts have been loaded and 
    /// the objects in the application have been created 
    /// and initialized.
    /// </summary>
    mainScreen.Init()
}

function endRequestHandler() {
    /// <summary>
    /// Raised before processing of an asynchronous 
    /// postback starts and the postback request is 
    /// sent to the server.
    /// </summary>
    
    // TODO: Add your custom processing for event
}

function beginRequestHandler() {
    /// <summary>
    /// Raised after an asynchronous postback is 
    /// finished and control has been returned 
    /// to the browser.
    /// </summary>

    // TODO: Add your custom processing for event
}

 

The line:

this.mainModalExtender = $find('mbMain');

initializes the variable mainModalExtender with extender client object. The object can be found on the page using $find function. This function is a part of ASP.NET AJAX framework, and it is responsible for locating for us behaviors on the page. You can read more information about the function in official AJAX documentation.

Complete Page markup is:

 

<%@ 
    Page 
    Language="C#" 
    AutoEventWireup="true"  
    CodeFile="Default.aspx.cs" 
    Inherits="_Default" 
    Theme="Default" %>

<%@ 
    Register 
    assembly="AjaxControlToolkit" 
    namespace="AjaxControlToolkit" 
    tagprefix="AjaxToolkit" %>

<!DOCTYPE html 
    PUBLIC "-//W3C//DTD 
    XHTML 1.0 
    Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    >

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>
    Using AjaxControlToolkit ModalPopup 
    Control to Show Alert Dialog 
    Instead of Javascript "alert" Popup Box
    </title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager 
        EnablePageMethods="true" 
        ID="MainSM" 
        runat="server" 
        ScriptMode="Release"
        LoadScriptsBeforeUI="true">
        <Scripts>
            <asp:ScriptReference 
                Path="~/Scripts/Main.js" />
        </Scripts>
    </asp:ScriptManager>
    <div>
        Click on the button show client-side alert
        with contents
        <br />
        <br />
        <table 
            border="0" 
            width="100%"
            >
            <tr>
                <td>
                    Title:
                </td>
                <td>
                    Text:
                </td>
            </tr>
            <tr>
                <td>
                    <input 
                        type="text"
                        value=""
                        id="tbAlertTitle"
                        />
                </td>
                <td>
                    <input 
                        type="text"
                        value=""
                        id="tbAlertText"
                        />
                </td>
            </tr>
        </table>
        <input 
            value="Alert that text" 
            type="button" 
            onclick="mainScreen.ShowModal(
                $get('tbAlertTitle').value, 
                $get('tbAlertText').value
                );" 
            />
        <br />
        <br />
        <asp:Panel 
            ID="MPanel" 
            runat="server" 
            Style="display: none">
            <table 
                class="mainModalTable" 
                cellpadding="0" 
                cellspacing="0">
                <tr>
                    <td 
                        class="mainModaTableTD">
                        <table 
                            class="mainModalInnerTable" 
                            cellspacing="0" 
                            cellpadding="0">
                            <tr>
                                <td 
                                    class="mainModalInnerTableTD">
                                    <table 
                                        border="0" 
                                        width="100%" 
                                        cellspacing="0" 
                                        cellpadding="4">
                                        <tr>
                                            <td 
                                                class="mainModalDraggablePanelTD">
                                                <asp:Panel 
                                                    CssClass="mainModalDraggablePanel" 
                                                    ID="MPD" runat="server">
                                                    <span 
                                                        class="mainModalTitle" 
                                                        id="spanTitle" 
                                                        Text="">
                                                    </span>
                                                </asp:Panel>
                                            </td>
                                            <td 
                                                align="right" 
                                                class="mainModalDraggablePanelCloseTD">
                                                    <asp:ImageButton 
                                                        SkinID="CloseModal" 
                                                        runat="server" 
                                                        ID="clB" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td 
                                                class="mainModalContentsTD" 
                                                colspan="2">
                                                <div 
                                                    id="mainModalContents">
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                    </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </asp:Panel>
        <AjaxToolkit:ModalPopupExtender 
            ID="mpeModal" 
            runat="server" 
            PopupControlID="MPanel"
            TargetControlID="btnHid"
            BehaviorID="mbMain"
            BackgroundCssClass="modalBackground" 
            CancelControlID="clB"
            OnCancelScript="mainScreen.CancelModal();" />
        <asp:Button 
            runat="server" 
            ID="btnHid" 
            style="display:none;" />    
    </div>
    </form>
</body>
</html>

 

Also to make popup look nice, I created the following CSS file:

.mainModalTable
{
    border-width:0px;
    width:240px;
    background-color:#ecf4fc;
}
.mainModaTableTD
{
    border-left: 1px solid #ECE9D8; 
    border-right: 1px solid #716F64; 
    border-top: 1px solid #ECE9D8;
    border-bottom: 1px solid #716F64;
}
.mainModalInnerTable
{
    border-width:0px;
    width:100%;
}
.mainModalInnerTableTD
{
    border-left: 1px solid #FFFFFF; 
    border-right: 1px solid #ACA899; 
    border-top: 1px solid #FFFFFF;
    border-bottom: 1px solid #ACA899;
}
.mainModalDraggablePanelTD
{
    white-space:nowrap;
    background-color:#93b6e8;
    height: 15px; 
    width: 99%;
}
.mainModalDraggablePanelCloseTD
{
    background-color:#93b6e8;
    width:1%;
}
.mainModalDraggablePanel
{
    /*cursor:move; */
    width:100%;
}
.mainModalTitle
{
    color:#FFFFFF;
    font-weight:bold;
}
.mainModalContentsTD
{
    white-space:nowrap;
    background-color:White;
    width:95%;
}
 .modalBackground 
 {
    background-color:Silver;
    filter:alpha(opacity=30);
    opacity:0.3;
 }

 

Also I created a small Skin file:

 

<asp:ImageButton 
    runat="server" 
    SkinID="CloseModal" 
    Width="8" 
    Height="7" 
    ImageURL="~/App_Themes/Default/Img/close.gif" />

 

That's it. This is the first article of series of articles that I am going to write about using ModulPopup control.

I am going to write about:

How to load content into ModalPopup in background using ASP.NET AJAX page methods.

How to create alternative for javascript "confirm" function to use confirmation dialog from client/server script.

How to load UserControls in background using ASP.NET AJAX page methods.

And more..

2 comments:

Anonymous said...

Excellent article and demonstration. How would I go about using this code in a master page called from code behind?

Kirill Chilingarashvili said...

You can show the modal dialog from c# code of code behind file.
just use ScriptManager.RegisterStartuScript method:
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", String.Format("mainScreen.ShowModal('{0}', '{1}');", "Warning", "TestWarning"), true);

Regards,
Kirill