Ajaxify ASPNET page with jQuery and Page Method

Ajax provide greater flexibility and power to any website but sometime you may not want to create a separate ASMX file to provide functionality that you already have defined on your page's code behind file because you want to use it using Ajax and also as a fallback if JavaScript is disabled in some user's browser. In such situations, you can always take benefit of page methods defined in asp.net Ajax.

Today we will see how we can use a method from page's code behind file as web service method and call it using jQuery Ajax.

Screen shot:

Key to convert method to web service like functionality is WebMethod attribute and static keyword as shown below:

[WebMethod]

public static string GetAuthorInfo(string name)

{

string result = "";

switch (name)

{

case "Nehaa":

result = "<H3>Nehaa Vishwakarma</H3>Author: DevTechie.com";

break;

case "Anoop":

result = "<H3>Anoop Tomar</H3>Author: DevTechie.com";

break;

default:

result = "Invalid Selection!";

break;

}

return result;

}

 

As you can see we have defined above method as static and attributed it with WebMethod (include using System.Web.Services;).

After this we can treat this page just as any other web service call:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function () {

$('a').click(function (e) {

e.preventDefault();

GetAuthorInformation($(this).attr('href'));

 

});

});

 

function GetAuthorInformation(message) {

$.ajax({

type: "POST",

url: "PageMethods.aspx/GetAuthorInfo",

data: "{'name':'" + message+"'}",

contentType: "application/json",

dataType: "json",

success: function (data) { $('#contact').html(data.d); }

});

}

</script>

<style type="text/css">

#contact

{

background-color:lightYellow;

font-style:italic;

color:Gray;

border:solid 1px lightGray;

width:200px;

}

</style>

</head>

<body>

<form id="form1" runat="server">

 

<div>

<a href="Nehaa">Nehaa Vishwakarma</a><br />

<a href="Anoop">Anoop Tomar</a>

</div>

<div id="contact">

 

</div>

</form>

</body>

</html>

Tags: , , , , ,

AJAX | ASP.NET | jQuery