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

Server Side Parameterized Method Call Using JQuery

4.55/5 (7 votes)
27 Mar 2014CPOL 25.1K   3  
This demo shows how jquery calls the server side parameterized method.

Introduction

This is a C# project that demonstrates how client side scripting language (JQuery) is used to call server side parameterized method that is written in server side language (C#, VB).

Using the Code

Step 1

WebForm1.aspx page has some controls like button, textbox control. Textbox is used to get a message from client to pass it to server side method. On button click, div element shows the message received from server.

C++
<form id="form1" runat="server">
        <div>
            <asp:TextBox ID="Text1" runat="server" />
            <asp:Button ID="Button1" runat="server" Text="ClickMENow" />
            <br />
            <div id="myDiv"></div>
        </div>
 </form> 

Step 2

Use the following JQuery to make Ajax call to server side method:

C++
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script>
        $(document).ready(function () {
            $('#<%=Button1.ClientID %>').click(function () {
                $.ajax({
                    type: "POST",
                    url: "WebForm1.aspx/ServerSideMethod",
                    data: JSON.stringify({ 'p': $('#Text1').val() }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function (msg) {

                        $('#myDiv').text(msg.d);
                    },
                    error: function (x, e) { alert(x.responseText); }
                })
                return false;
            });
        });
    </script>

Step 3

Server side method in WebForm1.aspx.cs is followed by WebMethod attribute:

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

Points of Interest

The server side method must be static and prefixed by attribute [WebMethod].

License

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