One-Time Event Handler in ASP.Net Using jQuery

Introduction

In this article, you'll learn about the Event Handler in jQuery in the ASP.NET web application. The event handler of JavaScript is often associated with any element fired every time. Suppose we associate the click event handler with the click event of a link then after clicking on the link that link will invoke that event handler every time.

Clicking on that link makes an Ajax request to the server and that request returns some data that is loaded in some other element. If the data is retrieved then there is no need for the event handler to fire. The redundant Ajax request to the server creates a load on the server so it is unnecessary.

Now with the use of the One() method of jQuery we can avoid these unwanted Ajax requests. As an alternative, we can unsubscribe the click event handler when it is executed the first time. So, we need to create the event handler only one time.

So, let's proceed to how to use this One() method using the following sections:

  • Creating Web Application
  • Adding Entity Model
  • Adding WebForm and Script
  • Running Application

Creating Web Application

In this section, we'll create the ASP.NET web application in Visual Studio. Here, I am using Visual Studio 2013 to create this web application with a Web Forms Project Template. Use the procedure below.

Step 1: Open Visual Studio 2013 and click on "New Project".

Step 2: Select the ASP.NET web application and enter the name for the application.

Creating Web Application in VS 2013

Step 3: Select the Web Forms Project Template.

Web Forms Project Template

Visual Studio automatically creates the web application and adds some files and folders to the application.

Step 4: Now open the App_Start/RouteConfig.cs file and update the code with the highlighted code below:

  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     var settings = new FriendlyUrlSettings();  
  4.     settings.AutoRedirectMode = RedirectMode.Off;  
  5.     routes.EnableFriendlyUrls(settings);  
  6. } 

Adding Entity Data Model

In this section, we'll add the ADO.NET Entity Data Model to the application. Use the following procedure.

Step 1: Right-click on the application and click on Add New Item to add an ADO.NET Entity Data Model.

Step 2: Select the EF Designer for the database.

Entity Data Model Wizard

Step 3: Apply the credentials for the Connection string and select the Objects.

Objects in Entity Data Model Wizard

Adding WebForm and Script

Step 1: Right-click on the application in Solution Explorer and click on the Add New Item.

Step 2: Select WebForms with Master Page.

Adding Form with Master Page

Step 3: Select the appropriate Master Page as Site. Master

Step 4: Replace the code with the code below:

  1. <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">  
  2.     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" SelectMethod="GridView1_GetData">  
  3.         <Columns>  
  4.             <asp:BoundField DataField="StudentID" HeaderText="Student ID" />  
  5.             <asp:BoundField DataField="StudentName" HeaderText="Student Name" />  
  6.             <asp:BoundField DataField="StudentSex" HeaderText="Student Sex" />  
  7.             <asp:HyperLinkField Text="Get City" />  
  8.         </Columns>  
  9.     </asp:GridView>  
  10. </asp:Content> 

Step 5: Enter the code for accessing the database table in the GridView as in following:

  1. namespace EventHandlerApp  
  2. {  
  3.     public partial class WebForm1 : System.Web.UI.Page  
  4.     {  
  5.         protected void Page_Load(object sender, EventArgs e)  
  6.         {  
  7.         }  
  8.         public IQueryable GridView1_GetData()  
  9.         {  
  10.             MyDatabaseEntities MyDb = new MyDatabaseEntities();  
  11.             var Query_Data = from db in MyDb.Students  
  12.                              orderby db.ID  
  13.                              select new  
  14.                              {  
  15.                                  StudentID = db.ID,  
  16.                                  StudentName = db.Name,  
  17.                                  StudentSex = db.Sex  
  18.                              };  
  19.             return Query_Data;  
  20.         }  
  21.         [WebMethod]  
  22.         public static string getcity(int stuid)  
  23.         {  
  24.             MyDatabaseEntities MyDb = new MyDatabaseEntities();  
  25.             var data = from db in MyDb.Students  
  26.                        where db.ID == stuid  
  27.                        select db.City;  
  28.             return data.SingleOrDefault().ToString();  
  29.         }  
  30.     }  
  31. } 

Step 6: Now add the Scripting code and update the webform code with the code below:

  1. <script src="Scripts/jquery-1.10.2.js"></script>  
  2. <script>  
  3.     $(document).ready(function () {  
  4.         $("a").one("click"function (evt) {  
  5.             debugger;  
  6.             var stu_id = $(evt.target).closest("tr").children(":first-child").text();  
  7.             $.ajax({  
  8.                 url: 'WebForm1.aspx/getcity',  
  9.                 type: "POST",  
  10.                 data: "{'stuid':'" + stu_id +"'}",  
  11.                 async: false,  
  12.                 contentType: "application/json",  
  13.                 success: function (final) {  
  14.                     debugger;  
  15.                     alert(final.d);  
  16.                 },  
  17.                 error: function () {  
  18.                     debugger;  
  19.                     alert('error');  
  20.                 }  
  21.             });  
  22.         });  
  23.     });  
  24. </script>   

In the code above the One() method is used to wire a one-time event handler to all the links in the web form. There are two parameters passed in the method, the first one is the type of event that is clicked and the second one is the event handler function.

Running Application

Step 1: Open the Site.Master page and update the following code with the highlighted code:

  1. <ul class="nav navbar-nav">  
  2.     <li><a runat="server" href="~/">Home</a></li>  
  3.     <li><a runat="server" href="~/About">About</a></li>  
  4.     <li><a runat="server" href="~/Contact">Contact</a></li>  
  5.     <li><a runat="server" href="~/WebForm1.aspx">Data</a></li>  
  6. </ul> 

Step 2: Run the application the click on the Data as in the following:

Main Web Form in VS 2013

Step 3: Click on the Get City Link, that shows an alter message that contains the city name.

Alert Message in Web Form

That's it.

Summary

This article explained how to use a one-time event handler with the One() method of jQuery in ASP.NET. Thanks for reading and Happy Coding.


Similar Articles