65.9K
CodeProject is changing. Read more.
Home

Calling a C# server side method with parameters using jQuery

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (2 votes)

Sep 9, 2011

CPOL
viewsIcon

35526

How to call a C# server side method with parameters using jQuery.

Design a Test.aspx page:

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

Design Test.aspx.cs:

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

Design the client script:

$(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.