jQuery is a powerful tool that can be used to enhance our ASP.NET application.
In the time of development, we often face problems 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 are lots of ways to to this using traditional AJAX like ASP.NET AJAX. But if we consider the hassle related to UpdatePanel
, then we can find a few people who will go for it.
Let's see how we can achieve this sort of Magic in our application easily with JQuery!
For the sake of 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" 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 let's write one method in code behind, i.e., in aspx.cs file that will do the actual db operation.
[WebMethod]
public static string fetchData(string someParameter)
{
string result = string.Empty;
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 encounters some error.
Just use this concept and be a magician of JQuery in ASP.NET!!!