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:

<a href="#" id="add">Add New</a>
then add this

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

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.

Regards,
Hajan

Published Monday, May 30, 2011 9:24 PM by hajan
Filed under: , , ,

Comments

# re: Call ASP.NET server side method from jQuery UI Dialog

Wednesday, June 1, 2011 3:41 PM by eric

great article for jQuery and Asp.net, but would be great utility download the project

# re: Call ASP.NET server side method from jQuery UI Dialog

Wednesday, June 1, 2011 3:59 PM by hajan

Hi eric,

Now you can download the source code from the link at the end of this blog post (there is update!).

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, June 2, 2011 11:24 AM by eric

thanks a lot for the link, the project works great!

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, June 2, 2011 12:11 PM by hajan

Eric, you are welcome :)!

Thanks for the comments.

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, June 7, 2011 9:35 AM by Benny

i cannot download demo from above link. could you share me a copy? thxs

cooleader_xu@hotmail.com

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, June 7, 2011 2:06 PM by hajan

@Benny, I sent you the source via mail ;)! Enjoy.

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, August 25, 2011 12:46 AM by lexcpe

I tried your code but when I push the "Add" button it always return error message

"Error! Try again..."

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, August 25, 2011 6:52 AM by hajan

@lexcpe, can you please try to debug the ajax request using client-side debuggers such as IE Developer Tools or Firebug? There are several possible reasons you can get Ajax Error. Please check what happens on client side and if you can't figure out, tell me the status error code that you receive. Also, try to read the post once again, maybe you are missing something?

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, September 20, 2011 4:00 AM by Govardhan

Thank you boss, thank you very much, I got it...........

# re: Call ASP.NET server side method from jQuery UI Dialog

Wednesday, October 19, 2011 12:29 PM by kubiczek

Hi, is it possible to add regularexpression validation to the textboxes and button add that would validate it? Great job!

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, October 25, 2011 6:41 PM by hajan

kubiczek, yes, you can use jQuery validate plugin to add regular expression validation easily... Check this example: stackoverflow.com/.../jquery-validate-how-to-add-a-rule-for-regular-expression-validation

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, November 17, 2011 1:18 PM by hajan

Edgard, try again... the link is working fine. I just tested it now.

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, November 17, 2011 6:41 PM by Edgard

Sorry,I didn't realize you had to have an account to download it :(

# re: Call ASP.NET server side method from jQuery UI Dialog

Thursday, November 17, 2011 7:33 PM by hajan

Edgard, no, you don't need to have an account... please double-check.

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, April 10, 2012 9:42 AM by Malay

This is the best article i have ever read which explains how to call server side method from client using jQuery. Simply best. Thanks a ton.

# re: Call ASP.NET server side method from jQuery UI Dialog

Friday, April 20, 2012 9:56 AM by Sanket

HI, i want to user not satic method of asp.net server side method on add button, can u please tell me how i can use non static method?

Thanks in advance

# re: Call ASP.NET server side method from jQuery UI Dialog

Monday, April 30, 2012 1:45 AM by Eloisa

When some one searches for his necessary thing, therefore

he/she wishes to be available that in detail, thus that thing is maintained over here.

# re: Call ASP.NET server side method from jQuery UI Dialog

Monday, September 10, 2012 10:52 AM by German

Hi,

very helpfull

thanks a lot.

Greetings.

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, October 16, 2012 12:09 PM by frd80

If the data already exists in the database how do I get the dialog to display that the name already exists in the database?

# re: Call ASP.NET server side method from jQuery UI Dialog

Wednesday, February 6, 2013 6:18 AM by Ankur

I tried code but when I click the "Add" button it always return error message

"Error! Try again..."

Thanks

Please help

# re: Call ASP.NET server side method from jQuery UI Dialog

Tuesday, February 12, 2013 7:52 AM by Meenakshi Moolani

while clicking AddNew link  div gets opens  but it is not disabling back part .. plz help in that

Leave a Comment

(required) 
(required) 
(optional)
(required)