Call ASP.NET server side method from jQuery UI Dialog

JQuery UI Dialog is great feature from the jQuery UI Framework. If you already work with it, you may have faced some issues when you want to make server-side posts directly from buttons inside your jQuery UI Dialog. JQuery UI Dialog has buttons parameter which helps us add our custom buttons in the bottom of the dialog itself. However, since it’s client-side html control, in order to make server-side post, we have to use Ajax based approach. Let’s get to an example… First of all, we need to have the jQuery and jQuery UI libraries and jQuery UI CSS files loaded:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/themes/redmond/jquery-ui.css" rel="stylesheet"
        type="text/css" />
Now, once we have loaded our jQuery files, we will add the HTML/ASPX code we will use for our demo. HTML/ASPX Inside body – form tag (if you work with asp.net mvc, you don’t have form), first add the following line: [html]<a href="#" id="add">Add New</a>[/html] then add this [html] <div class="addNew" title="Add new Person"> <table> <tr> <td>Name</td> <td><asp:TextBox ID="txtName" runat="server" /></td> </tr> <tr> <td>Surname</td> <td><asp:TextBox ID="txtSurname" runat="server" /></td> </tr> <tr> <td>Age</td> <td><asp:TextBox ID="txtAge" runat="server" /></td> </tr> </table> </div> [/html] This will be the ASPX that will display once the Add New is clicked. The end result will be displayed using Repeater control
<asp:Repeater ID="rptShowItems" runat="server">
    <HeaderTemplate>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Surname</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
    </HeaderTemplate>
    <ItemTemplate>
                <tr>
                    <td><%# Eval("Name") %></td>
                    <td><%# Eval("Surname") %></td>
                    <td><%# Eval("Age") %></td>
                </tr>
    </ItemTemplate>
    <FooterTemplate>
            </tbody>
        </table>
    </FooterTemplate>
</asp:Repeater>
So, as you can already notice, our data source collection has three parameters Name, Surname and Age. Here is the complete code in code-behind:
using System;
using System.Collections.Generic;
using System.Web.Services;

public partial class MyWebPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static bool AddNewItem(string name, string surname, int age)
    {
        Person person = new Person() { Name = name, Surname = surname, Age = age };

        //add your logic to insert item into database

        //we will always return true here, in real life, this of course can't be always true ;)
        return true;
    }
}

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}
The code is pretty simple. We have Person class with Name, Surname and Age, and AddNewItem static method that accepts three parameters and return true. In real life scenario this won’t be always true, but will depends if the insertion has succeeded. Moreover, this method is decorated with WebMethod attribute in order to make it accessible to call using Ajax from client-side. Now, the jQuery Ajax part.
<script type="text/javascript">
    $(function () {
        $(".addNew").dialog({
            autoOpen: false,
            width: 300,
            height: 300,
            modal: true,
            close: function (event, ui) {
                location.reload(false);
            },
            buttons:
            {
                "Add": function () {
                    //add functionality
                    //make ajax post
                },
                "Cancel": function () {
                    //cancel
                }
            }
        });

        $("#add").click(function (event) {
            event.preventDefault();
            $(".addNew").dialog("open");
        });
    });
</script>
With this code, we mainly attach the jQuery UI Dialog to .addNew element, so it will become invisible by default and will be opened once we make dialog(“open”). In the dialog we have several properties that set the default behavior such as width/height, autoOpen is set to false, modal is set to true, and we have function on close event (location.reload(false)) which will reload page once we close the dialog. The last property is buttons where we have two buttons Add and Cancel. As you can see, both has callback functions that will run once we click the corresponding button. As you can notice by the comments added in advance, we will write the Ajax post function inside Add button function, while in Cancel, we will make only dialog to close. The last part of the code is wiring up function to the click event of #add selector. We prevent the default element behavior and then trigger dialog open.  In other words, once we click Add new link, the dialog will open. jqueryuidialog_addnew_1 At this stage, only ‘X’ button is working :). So, now lets add the function which will call the AddNewItem method with supplied parameters once we click ‘Add’ button Both functions in buttons:
buttons:
{
    "Add": function () {
        var name = $("#<%= txtName.ClientID  %>").val();
        var surname = $("#<%= txtSurname.ClientID %>").val();
        var age = $("#<%= txtAge.ClientID %>").val();

        $.ajax({
            type: 'POST',
            url: 'MyWebPage.aspx/AddNewItem',
            data: '{"name":"' + name + '", "surname":"' + surname + '", "age":' + age + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.d) {
                    alert("Successfully added new item");
                }
            },
            error: function () {
                alert("Error! Try again...");
            }
        });
    },
    "Cancel": function () {
        $(this).dialog("close");
    }
}

You have to pay attention on the json string parameter names. These has to be the same with the parameter names defined in the AddNewItem C# function. Besides the fact that we don’t bind any data in the repeater control, I have added this for you to help you have prepared code snippet in case you want to use such logic in your application and display the data immediately after inserting has successfully completed. If you have any questions, ask anytime. Download source code. I hope this was helpful.