Telerik MVC : Creating Standard MessageBox Dialogs

This website is no longer actively supported

Written by John DeVight on 11 May 2011 13:56
Last Updated by John DeVight on 31 Jul 2012 12:02

Download RAZOR Samples Project

Overview

I am developing an application where I want to be able to keep a consistent look-and-feel for "standard" messagebox dialogs. I am working with Telerik MVC, so using the Telerik Window Extension, I created standard Alert, Wait, Confirm and OK/Cancel dialogs.

Creating the Files Needed

  • In the ASP.NET MVC 3 Web Application\Shared\Partial folder, create a partial view called MessageBoxDialogs.cshtml.
  • In the ASP.NET MVC 3 Web Application\Scripts folder, create a jscript file called MessageBoxDialogs.js.

At the end of the MessageBoxDialogs.cshtml file, I added the following code:

@{
    Html.Telerik().ScriptRegistrar()
        .Scripts(scripts =>
            scripts.AddGroup("MessageBoxDialogs", group =>
                group.Add("~/Scripts/Shared/MessageBoxDialogs.js")
            )
        );
}

In the MessageBoxDialogs.js file, I added the following code:

var MessageBoxDialogs = {};
 
MessageBoxDialogs.ErrorIcon = _rootUrl + 'Content/images/icon-error.gif';
MessageBoxDialogs.InfoIcon = _rootUrl + 'Content/images/icon-info.gif';
MessageBoxDialogs.QuestionIcon = _rootUrl + 'Content/images/icon-question.gif';
MessageBoxDialogs.WarningIcon = _rootUrl + 'Content/images/icon-warning.gif';
MessageBoxDialogs.LoadingIcon = _rootUrl + 'Content/images/ajax-loader.gif';

Note: _rootUrl is defined in my Layout.cshtml page as:

<script type="text/javascript">
    var _rootUrl = "@Url.Content("~")";
</script>

Creating the Alert Dialog

In the MessageBoxDialogs.cshtml partial view I added the following code:

@{Html.Telerik().Window()
    .Name("AlertDialog")
    .Title("My Application")
    .Content(
        @<text>
            <div class="panelContent">
                <div class="tableRow">
                    <div class="tableColumn" style="width:50px; display:inline-block;">
                        <img alt="Alert Dialog Image" id="AlertDialog_Image" />
                    </div>
                    <div id="AlertDialog_MessageColumn" class="tableColumn" style="max-width:240px; display:inline-block;">
                        <span id="AlertDialog_Message"></span>
                    </div>
                </div>
                <div id="AlertDialog_ButtonRow" class="tableButtonRow" style="width:290px;">
                    <div class="tableColumn" style="width:100%; text-align:center;">
                        <button id="AlertDialog_OkButton" onclick="AlertDialog.OkButton_OnClick(); return false;">OK</button>
                    </div>
                </div>
            </div>
        </text>
    )
    .Height(100)
    .Width(300)
    .Draggable(false)
    .Resizable(resizing => resizing.Enabled(false))
    .Visible(false)
    .Modal(true)
    .ClientEvents(events => events.OnActivate("AlertDialog.Window_OnActivate"))
    .Effects(fx => fx.Zoom())
    .Render();
}

In the MessageBoxDialogs.js javascript file I added the following code:

var AlertDialog = function () {
    // Settings passed into the dialog.
    var _settings = null;
 
    /// <summary>
    /// Show the AlertDialog.
    /// <summary>
    /// <param name="settings" type="JSON object">
    /// Contains all the settings for the dialog.  Settings are:
    ///     - message [Required] : Message to be displayed to the user.
    ///     - icon [Required] : MessageBoxDialogs.xyz where xyz represents one of the icon types listed above.
    ///     - parent [Optional] : the parent of the dialog as a jQuery object.
    ///     - callback [Optional] : the function that gets called when the dialog is closed.</param>
    ///     - height [Optional] : New height for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 100px.
    ///     - width [Optional] : New width for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 300px.
    // </param>
    var ShowWindow = function (settings) {
        _settings = settings;
 
        try {
            if (_settings.height != null) {
                $('#AlertDialog').data('tWindow').setHeight(_settings.height);
            }
            if (_settings.width != null) {
                $('#AlertDialog').data('tWindow').setWidth(_settings.width);
                $('#AlertDialog_MessageColumn').css('max-width', (parseInt(_settings.width.replace('px', '') - 60) + 'px'));
                $('#AlertDialog_ButtonRow').css('width', (parseInt(_settings.width.replace('px', '') - 10) + 'px'));
            }
 
            $('#AlertDialog_Image').attr("src", _settings.icon);
            $('#AlertDialog_Message').text(_settings.message);
 
            // Open the dialog.
            var wnd = $('#AlertDialog').data('tWindow');
            wnd.center().open();
        }
        catch (e) {
            alert(e);
        }
    };
 
    var OkButton_OnClick = function () {
        var wnd = $('#AlertDialog').data('tWindow');
        wnd.close();
 
        if (_settings.callback != null) {
            _settings.callback.call(this);
        }
    };
 
    var Window_OnActivate = function (e) {
        $('#AlertDialog_OkButton').focus();
    };
 
    return {
        ShowWindow: ShowWindow,
        OkButton_OnClick: OkButton_OnClick,
        Window_OnActivate: Window_OnActivate
    };
} ();

To use the AlertDialog, I call the AlertDialog.ShowWindow function and pass in the appropriate settings. For example:

AlertDialog.ShowWindow({ message: "Message goes here", icon: MessageBoxDialogs.InfoIcon });

Creating the Wait Dialog

In the MessageBoxDialogs.cshtml partial view I added the following code:

@{Html.Telerik().Window()
    .Name("WaitDialog")
    .Title("My Application")
    .Content(
        @<text>
            <div class="panelContent">
                <div class="tableRow">
                    <div class="tableColumn" style="width:50px;">
                        <img alt="Wait Dialog Image" id="WaitDialog_Image" />
                    </div>
                    <div id="WaitDialog_MessageColumn" class="tableColumn" style="max-width:240px;">
                        <span id="WaitDialog_Message">Please wait...</span>
                    </div>
                </div>
            </div>
        </text>
    )
    .Height(50)
    .Width(200)
    .Draggable(false)
    .Resizable(resizing => resizing.Enabled(false))
    .Visible(false)
    .Modal(true)
    .Effects(fx => fx.Zoom())
    .Render();
}

In the MessageBoxDialogs.js javascript file I added the following code:

var WaitDialog = {};
 
// Settings passed into the dialog.
WaitDialog._settings = null;
 
/// <summary>
/// Show the WaitDialog.
/// <summary>
/// <param name="settings" type="JSON object">
/// Contains all the settings for the dialog.  Settings are:
///     - message [Required] : Message to be displayed to the user.
// </param>
WaitDialog.ShowWindow = function(settings) {
    WaitDialog._settings = settings;
 
    $('#WaitDialog_Image').attr("src", MessageBoxDialogs.LoadingIcon);
    $('#WaitDialog_Message').text(WaitDialog._settings.message);
 
    var wnd = $('#WaitDialog').data('tWindow');
    wnd.center().open();
}
 
WaitDialog.CloseWindow = function() {
    var wnd = $('#WaitDialog').data('tWindow');
    wnd.close();
}

To use the WaitDialog, I call the WaitDialog.ShowWindow function and pass in the appropriate settings. For example:

WaitDialog.ShowWindow({ message: "Message goes here" });
 
// Some code goes here
 
WaitDialog.CloseWindow();

Creating the Confirm Dialog

In the MessageBoxDialogs.cshtml partial view I added the following code:

@{Html.Telerik().Window()
    .Name("ConfirmDialog")
    .Title("Confirm")
    .Content(
        @<text>
            <div class="panelContent">
                <div class="tableRow">
                    <div class="tableColumn" style="width:50px;">
                        <img alt="Confirm Dialog Image" id="ConfirmDialog_Image" />
                    </div>
                    <div id="ConfirmDialog_MessageColumn" class="tableColumn" style="max-width:240px;">
                        <span id="ConfirmDialog_Message"></span>
                    </div>
                </div>
                <div id="ConfirmDialog_ButtonRow" class="tableButtonRow" style="width:290px;">
                    <div class="tableColumn" style="width:100%; text-align:center;">
                        <button id="ConfirmDialog_YesButton" onclick="ConfirmDialog.Button_OnClick('Yes'); return false;">Yes</button>
                        <span style="width:5px;">&nbsp;</span>
                        <button id="ConfirmDialog_NoButton" onclick="ConfirmDialog.Button_OnClick('No'); return false;">No</button>
                    </div>
                </div>
            </div>
        </text>
    )
    .Height(100)
    .Width(300)
    .Draggable(false)
    .Resizable(resizing => resizing.Enabled(false))
    .Visible(false)
    .Modal(true)
    .ClientEvents(events => events.OnActivate("ConfirmDialog.Window_OnActivate"))
    .Effects(fx => fx.Zoom())
    .Render();
}

In the MessageBoxDialogs.js javascript file I added the following code:

var ConfirmDialog = function () {
    // Settings passed into the dialog.
    var _settings = null;
 
    /// <summary>
    /// Show the ConfirmDialog.
    /// <summary>
    /// <param name="settings" type="JSON object">
    /// Contains all the settings for the dialog.  Settings are:
    ///     - message [Required] : Message to be displayed to the user.
    ///     - icon [Optional] : MessageBoxDialogs.xyz where xyz represents one of the icon types listed above.
    ///     - parent [Optional] : the parent of the dialog as a jQuery object.
    ///     - callback [Optional] : the function that gets called when the dialog is closed.</param>
    ///     - height [Optional] : New height for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 100px.
    ///     - width [Optional] : New width for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 300px.
    // </param>
    var ShowWindow = function (settings) {
        _settings = settings;
 
        try {
            if (_settings.height != null) {
                $('#ConfirmDialog').data('tWindow').setHeight(_settings.height);
            }
            if (_settings.width != null) {
                $('#ConfirmDialog').data('tWindow').setWidth(_settings.width);
                $('#ConfirmDialog_MessageColumn').css('max-width', (parseInt(_settings.width.replace('px', '') - 60) + 'px'));
                $('#ConfirmDialog_ButtonRow').css('width', (parseInt(_settings.width.replace('px', '') - 10) + 'px'));
            }
 
            $('#ConfirmDialog_Image').attr("src", _settings.icon == null ? MessageBoxDialogs.QuestionIcon : _settings.icon);
            $('#ConfirmDialog_Message').text(_settings.message);
 
            // Open the dialog.
            var wnd = $('#ConfirmDialog').data('tWindow');
            wnd.center().open();
        }
        catch (e) {
            alert(e);
        }
    };
 
    var Button_OnClick = function (button) {
        var wnd = $('#ConfirmDialog').data('tWindow');
        wnd.close();
 
        if (_settings.callback != null) {
            _settings.callback.call(this, { result: button });
        }
    };
 
    var Window_OnActivate = function (e) {
        $('#ConfirmDialog_YesButton').focus();
    };
 
    return {
        ShowWindow: ShowWindow,
        Button_OnClick: Button_OnClick,
        Window_OnActivate: Window_OnActivate
    };
} ();

To use the ConfirmDialog, I call the ConfirmDialog.ShowWindow function and pass in the appropriate settings. For example:

// Display a confirm dialog that executes a callback function to display an alert dialog with the choice that the user made.
ConfirmDialog.ShowWindow({
    message: "Do you want to save?", 
    callback: function(response) {
        AlertDialog.ShowWindow({ message: "You clicked on: " + response.result, icon: MessageBoxDialogs.InfoIcon });
    }
});

Creating the OK/Cancel Dialog

In the MessageBoxDialogs.cshtml partial view I added the following code:

@{Html.Telerik().Window()
    .Name("OkCancelDialog")
    .Title("OK/Cancel")
    .Content(
        @<text>
            <div class="panelContent">
                <div class="tableRow">
                    <div class="tableColumn" style="width:50px;">
                        <img alt="OK Cancel Dialog Image" id="OkCancelDialog_Image" />
                    </div>
                    <div id="OkCancelDialog_MessageColumn" class="tableColumn" style="max-width:240px;">
                        <span id="OkCancelDialog_Message"></span>
                    </div>
                </div>
                <div id="OkCancelDialog_ButtonRow" class="tableButtonRow" style="width:290px;">
                    <div class="tableColumn" style="width:100%; text-align:center;">
                        <button id="OkCancelDialog_OkButton" onclick="OkCancelDialog.Button_OnClick('OK'); return false;">OK</button>
                        <span style="width:5px;">&nbsp;</span>
                        <button id="OkCancelDialog_CancelButton" onclick="OkCancelDialog.Button_OnClick('Cancel'); return false;">Cancel</button>
                    </div>
                </div>
            </div>
        </text>
    )
    .Height(100)
    .Width(300)
    .Draggable(false)
    .Resizable(resizing => resizing.Enabled(false))
    .Visible(false)
    .Modal(true)
    .ClientEvents(events => events.OnActivate("OkCancelDialog.Window_OnActivate"))
    .Effects(fx => fx.Zoom())
    .Render();
}
var OkCancelDialog = function () {
    // Settings passed into the dialog.
    var _settings = null;
 
    /// <summary>
    /// Show the OkCancelDialog.
    /// <summary>
    /// <param name="settings" type="JSON object">
    /// Contains all the settings for the dialog.  Settings are:
    ///     - message [Required] : Message to be displayed to the user.
    ///     - icon [Optional] : MessageBoxDialogs.xyz where xyz represents one of the icon types listed above.
    ///     - parent [Optional] : the parent of the dialog as a jQuery object.
    ///     - callback [Optional] : the function that gets called when the dialog is closed.</param>
    ///     - height [Optional] : New height for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 100px.
    ///     - width [Optional] : New width for the Confirm dialog.  Format should be <value>px.  For example: 500px.  Default is 300px.
    // </param>
    var ShowWindow = function (settings) {
        _settings = settings;
 
        try {
            if (_settings.height != null) {
                $('#OkCancelDialog').data('tWindow').setHeight(_settings.height);
            }
            if (_settings.width != null) {
                $('#OkCancelDialog').data('tWindow').setWidth(_settings.width);
                $('#OkCancelDialog_MessageColumn').css('max-width', (parseInt(_settings.width.replace('px', '') - 60) + 'px'));
                $('#OkCancelDialog_ButtonRow').css('width', (parseInt(_settings.width.replace('px', '') - 10) + 'px'));
            }
 
            $('#OkCancelDialog_Image').attr("src", _settings.icon == null ? MessageBoxDialogs.QuestionIcon : _settings.icon);
            $('#OkCancelDialog_Message').text(_settings.message);
 
            // Open the dialog.
            var wnd = $('#OkCancelDialog').data('tWindow');
            wnd.center().open();
        }
        catch (e) {
            alert(e);
        }
    };
 
    /// <summary>
    /// Event handler for when the OK or Cancel button is clicked.
    /// <summary>
    /// <param name="button" type="string">"OK" if the OK button was clicked, "Cancel" if the Cancel button was clicked.</param>
    var Button_OnClick = function (button) {
        var wnd = $('#OkCancelDialog').data('tWindow');
        wnd.close();
 
        if (_settings.callback != null) {
            _settings.callback.call(this, { result: button });
        }
    };
 
    var Window_OnActivate = function (e) {
        $('#OkCancelDialog_OkButton').focus();
    };
 
    return {
        ShowWindow: ShowWindow,
        Button_OnClick: Button_OnClick,
        Window_OnActivate: Window_OnActivate
    };
} ();

To use the OkCancelDialog, I call the OkCancelDialog.ShowWindow function and pass in the appropriate settings. For example:

// Display an ok/cancel dialog that executes a callback function to display an alert dialog with the choice that the user made.
OkCancelDialog.ShowWindow({
    message: "There are changes that have not been saved.  Are you sure you want to exit?", 
    icon: MessageBoxDialogs.WarningIcon, 
    callback: function(response) {
        AlertDialog.ShowWindow({ message: "You clicked on: " + response.result, icon: MessageBoxDialogs.InfoIcon });
    }
});

References

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License