Wednesday, September 5, 2012

jQuery UI - Modal Message

I was always not good in designing nice web sites, but this jQuery UI JavaScript library is there to help me on that. Today I am going to write about how to show a nice message box, which is a modal using jQuery UI.

First I need to have jQuery and jQuery UI libraries installed on my web application. I can easily use NuGet to do the installation.

Untitled
Installing jQuery library

Untitled1
Installing jQuery UI library

Then I have selected a theme from jQuery UI Themes. There are a lot of themes available and even you can customize the themes. I have downloaded a theme and put it into themes folder under Content folder.
Untitled2
Adding a theme
Then I have added following lines to the master page.
    <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="Content/themes/redmond/jquery-ui-1.8.22.custom.css" rel="stylesheet" type="text/css" />
I am adding a div to my page, and it will be the modal.
    <div id="dialog-alert" title="Message">

    </div>
I am writing a method in the code behind file which will contain the JavaScript function.
        private void ShowJqueryMessage(string message)
        {
            try
            {
                //Initialize the stringbuilder object to append javascript
                StringBuilder sb = new StringBuilder();
                sb.Append("$(function() { ");
                sb.Append("$('#dialog-alert').empty();");
                sb.Append("$('#dialog-alert').append('" + message + "');");
                sb.Append(" $('#dialog-alert').dialog({");
                sb.Append("    width: 350,");
                sb.Append("buttons: {");
                sb.Append("'Close': function () {");
                sb.Append("$('#dialog-alert').dialog('close');");
                sb.Append("}");
                sb.Append("   }");
                sb.Append(" });");
                sb.Append("});");
                //Register the script on page startup
                ClientScript.RegisterStartupScript(typeof(Page), "myscript", sb.ToString(), true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Then in my button click event I am calling the method.
        protected void Button1_Click(object sender, EventArgs e)
        {
            ShowJqueryMessage("Message.");
        }
Untitled3
Message in the modal

That's it. Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment