Thursday, December 24, 2020

Understand jQuery Ajax Function: Call Code-behind C# Method

 In this article, we will learn how to implement an ajax method in jQuery. There is no need to explain that ajax is one of the strong pillars of the future of web development. Since ajax is a concept or technique we can implement ajax with any web development platform. It is possible to implement ajax with PHP or with JSP or with ASP.NET or with many other technologies. Since we are learning .NET, in this article we will explain ajax in the context of C# .NET.

 
The experienced developer will say that there are two possible ways to implement ajax in an ASP.NET web application. The first one and the worst one is using an update panel. And the best one is using a jQuery ajax function.
 
Hmm...Many developers will not agree with my straight-forward conclusion. But if you search a little in the WWW and talk about .NET savvy then you may agree with me.
 
The reason why an update panel is not feasible is, when we add more than a few update panels on the same page, the performance of the page will decrease automatically. So, people don't like update panels much. It's cool for small ajax implementations.
 
And the next one is using an ajax method of jQuery. In this article, we will implement that. Using the jQuery ajax method we can call nearly any function (code behind) and various services, like a traditional Web service, WCF, WEB-API, and so on. In this article, we will learn each of them one by one.
 
Call function in Code-behind
 
Sometimes, the situation exists where we need to call a C# function defined in code-behind on the same page using a jQuery ajax method. Let's see how to do that.
 
Step 1: Create an ajax function in an .aspx page.
 
Use one .aspx page with the following code.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
  7.  <script>  
  8.      $(document).ready(function () {  
  9.          $.ajax({  
  10.              type: "POST",  
  11.              url: "JavaScript.aspx/GetData",  
  12.              contentType: "application/json; charset=utf-8",  
  13.              dataType: "json",  
  14.              success: function (response) {  
  15.                  $("#Content").text(response.d);  
  16.              },  
  17.              failure: function (response) {  
  18.                  alert(response.d);  
  19.              }  
  20.          });  
  21.      });  
  22.  </script>  
  23. </head>  
  24. <body>  
  25. <form id="frm" method="post">  
  26.     <div id="Content">  
  27.     </div>  
  28. </form>
  29. </body>
  30. </html>  
The code is very simple. Within the head section we are loading the jQuery pulgin from Google's CDN. There is a little advantage in loading the jQuery plug-in from the CDN, we will explain them later. Then we have defined the ajax function to call the C# function asynchroniously. The ajax function has a few properties, let's explain a few of them.
  • type: This is nothing but a request type. Here we are making a POST request type. We will explain various types in the following articles.
  • URL: This is nothing but the location of a C# function. Here we have provided a page name/path at first and then the method name followed by '/'. We can provide the URL of the remote server.
  • data-type: This defines in which form the data will pass. In other words, what the encoding scheme is for the data passed in. For example, we can send data in JSON or XML format.
  • Success and failure: Both are callback functions, after a successful ajax request the success function will execute and after failure, the failure function will execute.
Within the success function, we are getting data and pushing it to the DIV tag that was defined in the body portion of the HTML page.
 
Step 2: Define C# function in code-behind
 
Now we need to define the GetData() method in code-behind. Go to the code-behind portion of the same page and define the following method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Web.Services;  
  8. namespace WebApplication  
  9. {  
  10.     public partial class JavaScript : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.         }  
  15.         [WebMethod]  
  16.         public static string GetData()  
  17.         {  
  18.             return "This string is from Code behind";  
  19.         }  
  20.     }  
  21. }  
The concept is, we need to specify the method as WebMethod by the same attribute, otherwise the ajax function cannot call it and for that we need to include the "Sysyem.Web.Services" namespace.
 
One more point to be explained. When we call a C# function in code-behind, the function must be defined as a static function, otherwise, the ajax function cannot call it. Here is a sample output.
 
 Output
 
Return JSON data to ajax function
 
If you observe the preceding example closely, you will find that we are working with JSON data (as we specified in the jQuery ajax method) but we are returning a string? The concept is, the JSON data is nothing but a simple string. So we can treat the string as JSON data (let's not consider the format and rule of JSON data). So, in this example, we will create one List in the C# method and we will convert it to serializable JSON format and then we will return it to the jQuery ajax method. Have a look at the following example.
 
Step 1: Create code-behind method in .aspx page
 
Here is the modified version of our existing Web Method.
  1. [WebMethod]  
  2. public static string GetData()  
  3. {  
  4.     Dictionary<stringstring> name = new Dictionary<stringstring>();  
  5.     name.Add("1""Sourav Kayal");  
  6.     name.Add("2""Ram mishra");  
  7.     string myJsonString = (new JavaScriptSerializer()).Serialize(name);  
  8.     return myJsonString;  
  9. }  
The body is very simple, We have just defined the Dictionary with both a key and value as a string. The reason is, the key and value must be a string or an object type when we serialize the Dictionary using the JavaScriptSerializer class, otherwise it will throw an error. Then we are returning a simple JSON string to our jQuery ajax function.
 
Step 2: Define JQuey ajax function
 
Here is the definition of the jQuery ajax function. The code is very similar to the example above. 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
  7.  <script>  
  8.      $(document).ready(function () {  
  9.          $.ajax({  
  10.              type: "POST",  
  11.              url: "JavaScript.aspx/GetData",  
  12.              contentType: "application/json; charset=utf-8",  
  13.              dataType: "json",  
  14.              success: function (response) {  
  15.                  var names = response.d;  
  16.                  alert(names);  
  17.              },  
  18.              failure: function (response) {  
  19.                  alert(response.d);  
  20.              }  
  21.          });  
  22.      });  
  23.  </script>  
  24. </head>  
  25. <body>  
  26. <form id="frm" method="post">  
  27.     <div id="Content">  
  28.     </div>  
  29. </form>  
  30. </body>  
  31. </html>  
For the sake of simplicity we have just shown the data in an alert box, anyway we can show it in a formatted style. In a future article we will learn various ways to process JSON data.
 
Here is the sample example.
 
Output1
 

Conclusion

 
In this article, we saw how to implement a simple jQuery ajax method to call a code-behind C# method. In a future article, we will learn to call any service method from the jQuery ajax method.

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...