Part 2: Showing ASP.NET Server-Side Messages in a Custom Dialog (Server-side without ASP.NET AJAX)

Updated (03/28/2011):

There were issues if you are using asp.net UpdatePanel and postback is coming from within the panel. So I have updated the code in the dowload and added a separate post to handle the issue. Please look at the Part-3: Include Messages from Server-Side – Using ASP.NET UpdatePanel

Scenario:

There are times when you want to display validation or error message(s) to the user in a pop-up dialog. These messages could be coming from client-side or server-side. In this multi-part series I am going to provide you with the code to accomplish this. Yes, I am not going to explain building from scratch but provided you with working sample, which you can integrate in your web site/application.

Background:

ASP.NET validation controls are great way to let users know about the constraints on your input controls. Using these controls you can display error message next to the control telling users what needs to be corrected.  You can check more about those controls here (msdn) or here (quickstarts).

One of the controls is ValidationSummary control. As the name suggests, it displays the summary of the validation i.e. it aggregates and displays the error messages for each failed validation. You can place this control anywhere on the page and not necessarily right next to any control. But if you are running out of space on the page, it has a property – ShowMessageBox – which displays the summary of error messages in a pop-up dialog. But unfortunately this message-box has a default look. There is no way to customize the UI for this dialog. Now if you are like me who want a customized UI, then ValidationSummary is not the control for you and so you need to keep reading.

So instead of using ValidationSummary, I have come up with a script that uses jQuery UI Dialog to display the error message summary.

Road Map:

Here is what I think will be the series like:

  1. Part-1: Client-side Validation Summary
  2. Part-2: Include Messages from Server-Side without ASP.NET AJAX
  3. Part-3: Include Messages from Server-Side using ASP.NET AJAX 

Requirements:

  • ASP.NET Validation Controls: You must be using ASP.NET Validation Controls. So you will need know at least how to use those controls.
  • jQuery UI Dialog: We are going to use jQuery and jQuery UI Dialog. You don’t need to know how they work as I have taken care of it. But you will need those libraries. As I will discuss below, you can download them and include them in your project or you can use CDN, as in the sample provided.
  • Styles: I have used jQuery UI smoothness theme  but also have some customization. You are free to use your own UI.

Download Available:

Click here to download

The download provided is an .aspx file which follows single page model i.e.  no separate code-behind but is included in same file. Also I have included javascript code in the head of the page instead of a separate file. Though there isn’t any custom styling of UI dialog but no doubt you can do it easily.

What’s in this part?

The sample I am providing in this part shows how we can show messages coming from server-side into jQuery UI Dialog.  Here is the screen-shot of which shows dialog with message from server-side.

validation_server

This part does not involve any ASP.NET Ajax.

Brief Explanation of the code:

a: error-messag div: This is mandatory for our code / dialog to work. This is the div to which we will hook the jQuery UI Dialog.

<div id="error-messages">
</div>

b: js code: Nothing fancy in the code there. The initializedialog method simply hooks-up our div to the jquery dialog. The showDialog  is the method which will be called by the injected script from server-side. It’s purpose it to append the message sent from server-side to the dialog and then open the dialog.

<script type="text/javascript">
        $(function () {
            initializedialog();
        });
        function initializedialog() {
            $("#error-messages").dialog({
                autoOpen: false,
                hide: 'blind',
                minHeight: 125,
                maxWidth: 300,
                show: 'blind',
                title: 'Error(s)!'
            });
        }
        
        //This function is called from the script injected from code-behind.
        function showDialog(message) {
            $("#error-messages").remove();
            $("#error-messages").append(message);
            $("#error-messages").dialog('open');
        }
    </script>

c: Server-side code block:

The code below does is add message to the messages list if textbox has “admin”. In this example we have only one message but you can add as many as you want. Then in the OnPreRender we check if there are any messages i.e. count>0, if so then create UI string. Then create script that we want to inject as startup script using RegisterStartupScript method of the ScriptManager.

<script runat="server">
    public List<string> messages = new List<string>();
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "admin")
        {
            lblSuccessMessage.Text = String.Empty;
            messages.Add("Invalid String: 'admin'");
        }
        else
        {
            lblSuccessMessage.Text = "You entered valid string: " + txtName.Text;
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        if (messages.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul>");
            foreach (string str in messages)
            {
                sb.Append("<li>" + str + "</li>");
            }
            sb.Append("</ul>");
            string script = "$(function(){initializedialog();showDialog(\"" + sb.ToString() + "\");});";
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
 
        }
        base.OnPreRender(e);
    }
</script>

 

Not Using ASP.NET AJAX:

If you are not using AJAX i.e. ScriptManager and UpdatePanel the code should still work if your application is ajax enabled. If not you need little modification to two lines:

//remove the initializationdialog
string script = "$(function(){showDialog(\"" + sb.ToString() + "\");});";
 
//use ClientScript.RegisterStartupScript instead of ScriptManager.RegisterStartupScript
Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "dialog", script, true);

Conclusion:

We just saw how we can show messages from server-side in jquery UI Dialog. Feel free to download the code and play with it. Let me know if there are any issues, questions or anything else.

Update: Please refer Part-3 if you are using ASP.NET UpdatePanel

3 Comments

  • Many many thanks. You show me the way how to show message from server side. I was using custom controls ; that were validated only from server side and i have to show a message box for errors.
    regards
    Dev

  • Hi Guru, I tried implementing the concept at my end. But it is not working for me. I am using vb.net. I need to show the server exception in modal dialog.

  • @shadab farrukh,
    Did you convert your code into VB.NET? Are you getting any errors?

Comments have been disabled for this content.