How to call Server Side function from Client Side in ASP.NET?

Call Server Side function from Client Side Code using PageMethods in ASP.NET and jQuery

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. Here we are using jQuery AJAX to call serverside method.

1. Create a new website.
2. Open the Default.aspx include jquery library to the page.
<script src=”Scripts/jquery-1.4.1.js” type=”text/javascript”></script>
3. Add an html button in the page

<input type=”button” value=”Get Methhod” id=”btnGetMethod” />

4. Go the Code behind file of the page and add a static method and mark them as WebMethod. Lets Say the method name is GetPageMethod which returns a status value

[System.Web.Services.WebMethod]        
public static string GetPageMethod()
{
      return “Welcome PageMethods”;
}

5. Go back to the aspx page and write the following jquery script.
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#btn1’).live(‘click’, function () {
$.ajax({
type: “POST”,
url: “Default.aspx/GetPageMethod”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (msg) {
alert(msg.d);
}
});
});

});

</script>
6. Run the application.

                                                       Author: Aneesh Sivan
Advertisements

One thought on “How to call Server Side function from Client Side in ASP.NET?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s