Click here to Skip to main content
Click here to Skip to main content

ASP.NET Server Side Messages & Client Validation Message Handling.

, 25 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Show different type of Client Side and Server side messages in a Modal box.

Introduction

Most of the time while developing web applications, we need to show server side messages at the client side in a dialog. Your server side messages can fall in any of the following categories:

  1. Error messages
  2. Success messages
  3. Information
  4. Warning messages

Many times, we also want to show the validation summary of the page in a modal dialog. There are so many jQuery plugins which help to achieve this, but I haven’t found them suitable for my scenario.

In this article, I will be showing how to show those messages in a presentable format at the client side. I am not going to explain the detailed code, it’s very simple and you can easily figure it out from the source code.

How to Use Validation Summary Control?

In simple words, ValidationSummary control is used for displaying a summary of all validation errors that occurred in a web page. Error messages displayed in this control are specified by the ErrorMessage property of each validation control.

For more details on this control, you can check this link.

ASP.NET has provided so may validation controls and we can write our own custom validation controls as per our requirement. Using these validation controls, we can show attached error messages anywhere in the page. For more details, you can check MSDN.

But many times, it doesn’t look good to show the error messages along with the control; we might want to see the summary all together. To support this, Microsoft has provided Validation Summary control. We will be using the Validation Summary control to show the messages in a modal box. There is a limitation of the ValidationSummary control that it only works with single validation group or overall page validation. If we have multiple validation groups being used in a page, in that case we need to have multiple Validation Summary controls in the page where each ValdiationSummary control targets a specific group.

In our scenario, our message control has used 7 different ValidationSummary controls assuming that one page can have at most 7 validation groups. In case your page has more than 7 ValdiationGroups in your page, you can add more Validation Summary Controls in the message control.

<asp:ValidationSummary ID="summary1" ValidationGroup="V1" runat="server" />
<asp:ValidationSummary ID="summary2" ValidationGroup="V2" runat="server" />
<asp:ValidationSummary ID="summary3" ValidationGroup="V3" runat="server" />
<asp:ValidationSummary ID="summary4" ValidationGroup="V4" runat="server" />
<asp:ValidationSummary ID="summary5" ValidationGroup="V5" runat="server" />
<asp:ValidationSummary ID="summary6" ValidationGroup="V6" runat="server" />
<asp:ValidationSummary ID="summary7" ValidationGroup="V7" runat="server" />

Output

Single Validation

4-Single_Validation.png

Multiple Validation Group

Group 1

5-Multiple_Validation.png

Group 2

6-Multiple_Validation.png

Error Message

2-Error.png

Warning Message

3-Warning.png

Success Message

1-Success.png

Implementation

To achieve the above types of messages, I have created a web user. Control contains some JavaScript code to show the messages in the div which looks like a modal box. You just need to drop the control in your Master page or in your page.

To invoke the client side validation, you need to attach a client side script to your button to show the validation summary.

Code for attaching the client script looks like the following code snippet:

  <asp:Button ID="Button2" ValidationGroup="V2" 
            runat="server" OnClick="Button1_Click" 
            OnClientClick="ValidateJs('V2');"
                        Text="Post" />

In the above code snippet, you need to attach OnClientClick event like OnClientClick="ValidateJs('V2');" where ‘V2’ is the Validation Group Name.

function ValidateJs(validationGroupName) {
        if (typeof (Page_ClientValidate) == 'function') {
            var validationResult = Page_ClientValidate(validationGroupName);
            if (validationResult == false) {

                if (!Page_IsValid) {
                    LoadMessage(validationGroupName);
                }
            }
        }
    }

The above function checks using Page_ClientValidate function if the provided group is valid (means it contains validation error or not) if some error is found and the page state is invalid for the validation controls, then the LoadMessage function is called which opens the modal dialog. The code for the LoadMessage is:

    function LoadMessage(grpName) {
        var header = document.getElementById("<%=lblHead.ClientID%>");
        var img = document.getElementById("<%=imgMsgType.ClientID%>");
        var tbl = document.getElementById("<%=tblMessage.ClientID%>");
        if (header != null && img != null && tbl != null) {
            img.src = "images/validation.png";
            header.innerHTML = "Validation Error [Group : " + grpName + "]";
            tbl.style.backgroundColor = "#AE1F24";
        }
        showPopup();
    }

How to Show Server Side Messages?

To identify different types of messages raised from the server, I have created an Enum which looks like the following code snippet:

    public enum MessageType
    {
        Success,
        Warning,
        Error
    }    

To show the server side messages, I have created one BasePage which inherits System.Web.UI.Page class and all of my page will be inheriting the BasePage class. The BasePage class looks like:

using ValidationMessage.Controls;

namespace ValidationMessage
{
    public class BasePage : System.Web.UI.Page
    {
        public void ShowErrorMessage(string message)
        {

            Show(message, MessageType.Error);
        }
        public void ShowWarningMessage(string message)
        {
            Show(message, MessageType.Warning);
        }
        public void ShowSuccessMessage(string message)
        {
            Show(message, MessageType.Success);
        }
        private void Show(string message, MessageType messageType)
        {
            if (Page.Master != null)
            {
                Message popMsg = Page.Master.FindControl("MsgControl") as Message;
                if (popMsg != null)
                {
                    popMsg.ShowPopMessage(message, messageType);
                }
            }
        }
    }
}    

If you want to show any message from the server side to the client side on any event, you just need to call the appropriate base class method as follows:

  protected void SuccessButton_Click(object sender, EventArgs e)
        {
            ShowSuccessMessage(
                string.Format(
                "{0}<br> Message: {1}<br> Time: {2}"
                ,"'SUCCESS' message sent by server."
                ,MessageText.Text
                ,DateTime.Now));
        }

        protected void ErrorButton_Click(object sender, EventArgs e)
        {
            ShowErrorMessage(
                string.Format(
                "{0}<br> Message: {1}<br> Time: {2}"
                , "'ERROR' message sent by server."
                , MessageText.Text
                , DateTime.Now));
        }

        protected void WarningButton_Click(object sender, EventArgs e)
        {
            ShowWarningMessage(
               string.Format(
               "{0}<br> Message: {1}<br> Time: {2}"
               , "'WARNING' message sent by server."
               , MessageText.Text
               , DateTime.Now));
        }

Client API

It's not always the case that we need to show the messages in a webpage from server side code only, there are many scenario where we want show the messages at client side using JavaScript code. To accommodate this, we will use the same message control so that the UI will look exactly the same in both the cases server side & client side messages.

To raise a client side message, I have written a JavaScript function ShowClientSide. This function expects four parameters:

  1. Header Image URL
  2. Header Text (Like “Warning”)
  3. Header background color
  4. Messages

JavaScript code of ShowClientSide is as follows:

function ShowClientSide(imgSrc, headerText, headerBGColor, messageText) {
        var header = document.getElementById("<%=lblHead.ClientID%>");
        var img = document.getElementById("<%=imgMsgType.ClientID%>");
        var tbl = document.getElementById("<%=tblMessage.ClientID%>");
        var spn = document.getElementById("<%=spnText.ClientID %>");
        if (header != null && img != null && tbl != null && spn!=null) {
            img.src = imgSrc;
            header.innerHTML = headerText;
            tbl.style.backgroundColor = headerBGColor;
            spn.innerHTML = messageText;
        }
        showPopup();       
    }

Note, you need to add above JavaScript function in the Message.ascx as we are using the <%=lblHead.ClientID%> and other inline tag in the function which are control specific.

You can invoke client side messages as follows:

ShowClientSide('images/validation.png', 'Client Side Message', 
	'#AE1F24','Message raised from client side script');

AJAX Support

Message control is wrapped within an UpatePanel to support any AJAX behavior. The UpdateMode property is set to “Always” so that UpdatePane controls content is updated on every postback that originates from anywhere on the page. In normal scenario, it’s not necessary that the message control is inside an update panel and all the messages are invoked within the update panel, messages can be invoked from any section of the page. UpdateMode=”Always” includes asynchronous postbacks from controls that are inside other UpdatePanel controls and postbacks from controls that are not inside UpdatePanel controls.

Conclusion

To simplify the messages, I have created one single web user control which can be used without much supporting code. Ideally, the message control should be a custom control in the form of library which I have not done as of now due to lack of time. I might update the article some time with the updated control.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Prakash Kalakoti
Technical Lead
India India
Its me Smile | :)

Comments and Discussions

 
GeneralMy vote of 5 PinmemberCarsten V2.012-Feb-14 21:52 
QuestionImplement for Wizards PinmemberMisael Perez11-Feb-14 8:04 
GeneralMy vote of 5 PinmemberArun Prakash.J6-Nov-12 19:18 
GeneralMy vote of 4 PinmemberKrunal Rohit30-Oct-12 3:24 
QuestionRate Pinmemberpatelraj24-May-12 21:01 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-Feb-12 17:51 
GeneralMy vote of 4 PinmemberAmit kumar pathak15-Dec-11 7:22 
QuestionRepack PinmemberJean Raath5-Oct-11 23:26 
GeneralMy vote of 5 Pinmemberkoolprasad200319-Jun-11 21:12 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti23-Jun-11 19:22 
GeneralMy vote of 5 Pinmvpthatraja14-Jun-11 4:49 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti23-Jun-11 19:22 
GeneralRe: My vote of 5 Pinmvpthatraja23-Jun-11 20:38 
GeneralMy vote of 4 PinmemberSChristmas14-Jun-11 3:05 
GeneralRe: My vote of 4 PinmemberPrakash Kalakoti23-Jun-11 19:22 
GeneralMy vote of 5 PinmemberTweakBird12-Jun-11 20:27 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti12-Jun-11 21:11 
GeneralGreat PinmemberMember 459066927-May-11 1:38 
GeneralRe: Great PinmemberPrakash Kalakoti27-May-11 1:52 
GeneralRe: Great PinmemberNicola Di Martino27-May-11 3:09 
GeneralRe: Great PinmemberPrakash Kalakoti27-May-11 3:17 
GeneralRe: Great PinmemberNicola Di Martino27-May-11 5:38 
GeneralMy vote of 5 PinmemberMonjurul Habib25-May-11 22:35 
nice one.
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti26-May-11 0:25 
GeneralMy vote of 5 PinmemberFilip D'haene24-May-11 5:34 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti24-May-11 18:59 
GeneralMy vote of 5 Pinmemberjawed.ace23-May-11 23:06 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti23-May-11 23:10 
GeneralMy vote of 5 Pinmembersaxenaabhi623-May-11 20:26 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti23-May-11 22:01 
GeneralMy vote of 5 PinmemberShashankSinghThakur19-May-11 7:32 
GeneralRe: My vote of 5 PinmemberPrakash Kalakoti19-May-11 16:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141015.1 | Last Updated 26 May 2011
Article Copyright 2011 by Prakash Kalakoti
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid