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.
<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:
<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:
[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]
.