Monday, 28 November 2011

Magic of JQuery in ASP.NET, Simplifying AJAX

jQuery is a powerful tool that can be used to enhance our ASP.NET Application.
In the time of development we often face problem like “need to show certain data based on a button click” or “need to implement tab in pages where each tab contains costly DB operation”.
There is lots of way to to this using traditional AJAX like ASP.NET AJAX. But if we consider the hassle related with UpdatePanel then we can find a few people who will go for it.
Lets see how we can achieve this short of Magic in our application easily with JQuery!
For simplicity lets assume that we have one aspx page with one div and one button. After clicking the button one extensive database operation will be held and the div’s inner html will be updated without page refresh.
Its to be noted that in order to leverage this facility of accessing Page Method through client script we need to add script manger and need to enable page method.
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="true"></asp:ScriptManager>


<asp:panel ID="divExtensiveData" runat="server"></asp:panel>


<asp:Button ID="btnFetchData" Text="Fetch Data" runat="server" OnClientClick="fetchData(); return false;" />
Now lets write one method in code behind i.e. in aspx.cs file that will do the actual db operatio

[WebMethod]
public static string fetchData(string someParameter)
{
string result = string.Empty;
/// Do extensive db operation
/// Assign value to result
return result;
}
Now we will get back to our aspx page and will write one method to access this page method.
<script type="text/javascript">
function fetchData(parameter)
 { 
  PageMethods.fetchData(parameter,dataFetched,dataNotFetched);
 }
function dataFetched(result)
{
 var panelID = '<%=divExtensiveData.ClientID %>';
 $("#"+panelID).html(result);
}
function dataNotFetched()
{
 var panelID = '<%=divExtensiveData.ClientID %>';
 $("#"+panelID).html("<h1>Error Occured.</h1>");
}
</script>
Now explaining the page method call from script. In our call to page method  I have given three parameters whereas the page method takes only one. The second one is just  a reference of the method that will be executed after successfully page method call and the third one is the reference of the method that will be called if the page method encounter some error.
Just use this concept and be a magician of JQuery in ASP.NET!!!

No comments :