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

Calling a C# server side method with parameters using jQuery

2.50/5 (2 votes)
9 Sep 2011CPOL 35.5K  
How to call a C# server side method with parameters using jQuery.

Design a Test.aspx page:


ASP.NET
<asp:TextBox ID="Text1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Click" />
<br />
<div id="myDiv"></div>

Design Test.aspx.cs:


C#
[WebMethod]
public static string ServerSideMethod(string paraml)
{
    return "Message from Server" + paraml;
}

Design the client script:


JavaScript
$(document).ready(function () {
    var name = 'stupid';
    $('#<%=Button1.ClientID %>').click(function () {
        $.ajax({
            type: "POST",
            url: "Default7.aspx/ServerSideMethod",
            data: "{'paraml': " + $("#Text1").val() + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                $('#myDiv').text(msg.d);
            }
        })
        return false;
    });
});

Now execute the script.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)