Mhazad's Blog

September 8, 2009

Magic of JQuery in ASP.NET, Simplifying AJAX

Filed under: AJAX, ASP.NET, JQuery — Tags: , , , , — Mahmudul Haque Azad @ 4:58 pm

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 do 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.

Let’s see how we can achieve this short of Magic in our application easily with JQuery!

For simplicity let’s 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.

It’s 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"

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

<asp:Button ID="btnFetchData" Text="Fetch Data" runat="server" OnClientClick="fetchData(); return false;" />

Now let’s write one method in code behind i.e. in aspx.cs file that will do the actual db operation.

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)

function dataFetched(result)
 var panelID = '<%=divExtensiveData.ClientID %>';
function dataNotFetched()
 var panelID = '<%=divExtensiveData.ClientID %>';
$("#"+panelID).html("<h1>Error Occured.</h1>");

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!!! CodeProject

Blog at