Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

4.67/5 (30 votes)
25 May 2011CPOL5 min read 113.1K   3.5K  
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.NET
<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.NET
<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.

JavaScript
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:

JavaScript
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:

C#
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:

C#
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:

C#
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:

JavaScript
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:

JavaScript
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)