Chuyển tới nội dung
Home » Ajax Call In Aspx Page | Partial Postback Using Updatepanel

Ajax Call In Aspx Page | Partial Postback Using Updatepanel

jquery ajax load aspx page

Using ajax() and ASP.NET Controls

If we use jQuery.ajax() instead of the ASP.NET UpdatePanel control, we will eliminate the ViewState as well as other overhead. An ajax() call will return just the requested data, which is exactly what we want.

Modifying an ASP.NET page to use jQuery.ajax requires replacing the control handlers with client-side jQuery functions and registering them to handle click events. It also involves adding server-side methods that the jQuery functions call to get the required data for populating the ASP.NET controls.

Client-Side – Handling ASP.NET Control Events

We can use jQuery to define a click handler for a button to replace the An asp:Button OnClick handler, as shown below:

$(“#btnLoadUsers”).click(function () { // Handle a button click });

vAnd a asp:GridView row click handler can be replaced as follows:

$(“#gridViewUsers”).delegate(‘tr’, ‘click’, function () { // Handle a GridView row click });

The comment lines in the examples above show where you would add the ajax() calls to get the data from the server.

Server-Side – Methods to Return Data

The code behind for handling the click events would need to be replaced with methods that simply return the requested data, such as the following:

[WebMethod] public static List

GetUsers() { return UserData.GetUsers(); } [WebMethod] public static UserData.UserDetails GetUserDetails(string id) { return UserData.GetUserDetails(id); }

Note that the methods need to be defined as

public static

, and decorated with the

[WebMethod]

attribute. The GetUserDetails() WebMethod shown above returns an object that defines a user. The UserDetails class returned by the WebMethod looks like this:

public class UserDetails { public int ID; public UserInfo Info; public string Address; public string City; public string State; public string PostalCode; }

The UserDetails class contains a UserInfo member, which looks like this:

public class UserInfo { public int ID; public string UserName; public string FirstName; public string LastName; }

That UsersDetails object will be sent back to the client as a JSON string defining the user.

Client-Side – Using ajax() to Call Data Methods

In order to use those WebMethods, define an ajax() call in your client code and specify the WebMethod name in the

url:

argument. The ajax() call to the GetUserDetails() WebMethod is shown below:

$(“#gridViewUsers”).delegate(‘tr’, ‘click’, function () { var req = $.ajax({ type: “POST”, url: “AspAjax.aspx/GetUserDetails”, contentType: “application/json; charset=utf-8”, dataType: “json”, data: “{ id: ” + id + “}” }); req.done( /* Add function here to handle success case */ ); req.fail( /* Add function here to handle error case */ ); });

Any parameters that are passed to a WebMethod are defined in the “data:” argument to the ajax() call. If the WebMethod takes no parameters, then use

data:"{}"

.

Note that the ajax() call allows us to define functions to be executed when the call is done and when it fails. The

done()

function defines how to process the data returned by the WebMethod. The

fail()

function defines how the web application should handle an unsuccessful ajax() call.

Also note that you can use the

success()

and

error()

ajax() parameters. There are also

success()

and

error()

functions, but they have been deprecated. The first usage shown below is a

success()

function, and has been deprecated. The second usage below is the

success()

parameter to the ajax() function, and can be used instead of the

done()

function.

$.ajax({}).success(function(){…}); $.ajax({ success: function(){…} });

In the example shown above an HTTP POST request method was used. That is the default, but the next section shows how to do the same with an HTTP GET request.

Client-Side – Making an HTTP GET jQuery.ajax() Request

There are times when we need to make a GET request instead of a POST request. Using a GET request might result in a slightly faster response than a POST because the latter has an additional Content-Length line in the header. A GET request is also more in line with REST guidelines for cases where you’re just getting data from the server. POST requests, however, have the advantage of keeping the request data out of the URL, thus hiding it from the user and from URL indexing services.

To make a GET request you need to add the following attribute to your WebMethod:

[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

You’ll also need to make the following modification to the

data:

line in your jQuery.ajax() call:

data: “id=” + id

After those changes you can specify that the ajax() call should use the GET method by modifying the

type:

line in your jQuery.ajax() call:

type: “GET”,

Client-Side – Examining the Server Response

The response from the UserDetails() WebMethod is a JSON string containing the requested data:

{“d”: { “__type”:”DataSource.UserData+UserDetails”, “ID”:2, “Info”: { “__type”:”DataSource.UserData+UserInfo”, “ID”:2, “UserName”:”bbrown”, “FirstName”:”Bill”, “LastName”:”Brown” }, “Address”:”6787 Spring St.”, “City”:”Dallas”, “State”:”TX”, “PostalCode”:”85858″ } }

You can see that the JSON string contains all of the members of the UserDetails object, including its UserInfo member.

Note also that the JSON string returned by a WebMethod contains one top-level name/value pair named . Before .NET 3.5, just the value string would be returned, but that was a security threat, since executable javascript could be injected by a malicious party. That javascript would then be executed in the browser. Changing the form of the json string to

{d:object}

resolved that, since that is not valid javascript.

Next we’ll look at how to parse that JSON data to populate ASP.NET controls on the page.

Client-Side – Using the WebMethod Response

The JSON data returned by the WebMethod can be easily accessed. If you look at it in the Developer Tools section you can see the return values:

The individual data items can be accessed as shown in the following examples:

var userName = data.d.Info.UserName; var address = data.d.Address;

To set the User Details GridView, you can directly manipulate the HTML that the GridView generates. This involves clearing out all but the first (header) row, then appending HTML to the GridView. The code for the

done()

function is as follows:

req.done(function (data) { $(“#gridViewUserDetails tr:not(:first-child)”).html(“”); $(“#gridViewUserDetails”).append( ”

UserName: ” + data.d.Info.UserName + ”

” + ”

First Name: ” + data.d.Info.FirstName + ”

” + ”

Last Name: ” + data.d.Info.LastName + ”

” + ”

Address: ” + data.d.Address + ”

” + ”

City: ” + data.d.City + ”

” + ”

State: ” + data.d.State + ”

” + ”

Zip: ” + data.d.PostalCode + ”

“); });

Client-Side – Examining ajax() Response Size

When using ajax(), the data transfer is drastically reduced. The two images below show the amount of data transferred when initially loading the user table and when clicking a row in that table to load user details.

The image above on the left shows that clicking the Load Users button results in a data transfer of 575 bytes, as shown below.

The image above on the right shows that clicking a row in the Users GridView control results in a transfer of 501 bytes, as shown below.

So, by using ajax() the size of the data transferred each time a row in the Users GridView is clicked is reduced from 5.6 KB to just 501 bytes. That’s a significant decrease in data which should result in a similar improvement in performance.

Introduction

Visual Studio is a great tool for developing web applications, but your site might end up being rather sluggish if you don’t design it to avoid large data transfers (postbacks) when pages are updated. Often, a developer will be tasked with solving this problem on an existing site and will not have the option of a major rewrite. This article shows how to modify an existing ASP.NET site to send much less data across the wire, and thus provide a more performant interface to its users. It also provides guidance to those creating a new ASP.NET site.

The focus of this article is to show how you can use jQuery and ajax() to greatly reduce the amount of data retrieved from the server when the user clicks a control on a page. By using ajax(), just the data necessary to update the page is retrieved, resulting in a faster response for the user.

An example application that demonstrates the methods discussed in this article is available for download here.

jquery ajax load aspx page
jquery ajax load aspx page

Replacing ASP.NET Controls with HTML

You might find, while you’re refactoring your code, that it makes sense to replace some of the ASP.NET controls with the corresponding HTML tags they render. The JQueryAjax page of the example application does that, replacing the asp:Button and asp:GridView controls with HTML input and table tags.

That example page defines the table structure for the Users table, but leaves the table body empty so it can be filled when the data arrives:

Users

Username First Name Last Name

The

done()

function that is called when the GetUsers() WebMethod returns uses the jQuery templating plugin (see references at the end of this article). In the JQueryAjax.js file, the template is used to add a table row for each record returned by GetUsers():

req.done(function (data) { var table = $(“#tblUsers tbody”); table.html(”); $(“#userRowTemplate”).tmpl(data.d).appendTo(table); });

The template used in that

done()

function is defined in the JQueryAjax.aspx file. The data passed to the template function contains the basic information for the user, along with an ID that is used to look up user details when a row is clicked. The template is shown below:

In other cases it might be better to retain the ASP.NET controls, especially in the case of the more complex ones, such as the Login or AdRotator controls. You might also have custom controls that you don’t want to replace. It only makes sense to replace ASP.NET controls if doing so provides some performance benefit or simplifies your code. The focus should be on reducing postback-related data transfers, and jQuery.ajax() can do that for you.

Another option is to define just the bare minimum of HTML controls on the page and retrieve the remaining controls with ajax() calls. The AjaxGetHtml page of the example application demonstrates this. The page the user initially loads has just a

button

and two

div

tags, one for the users table and one for user details. The WebMethods that are called by ajax() prepare the HTML that go into those

div

tags, and the jQuery

done()

methods that handle the returning data just plug it into the page.

Here’s the HTML for that example page:


Home


The method to handle the button click makes an ajax() call with a DataType of “html”:

var req = $.ajax({ type: “GET”, url: “AjaxGetHtml.aspx/GetUserDetails”, contentType: “application/json; charset=utf-8”, dataType: “html”, data: “id=” + id });

The GetUsers() WebMethod returns a string defining the HTML to be put into the Users

div

:

[WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)] public static string GetUsers() { var sb = new System.Text.StringBuilder(); sb.Append(@”

Users

“); sb.Append(@”

“); sb.Append(@”

“); sb.Append(@”

“); sb.Append(@”

“); sb.Append(@”

“); sb.Append(@””); sb.Append(@”

“); var users = UserData.GetUsers(); foreach (var user in users) { sb.Append(@”

“); } return sb.ToString(); }

Username Firstname Lastname
“); sb.Append(user.UserName); sb.Append(@” “); sb.Append(user.FirstName); sb.Append(@” “); sb.Append(user.LastName); sb.Append(@” “); sb.Append(user.ID); sb.Append(@”

The HTML string that is returned to the page is simply added to the Users

div

:

req.done(function (data) { $(“#userTableContainer”).append(data);

In a real-world application we probably wouldn’t send the html on every click, since sending just the data as a JSON string is more efficient. There might be cases, however, where that would make sense. For instance, suppose we had a page that presented several different complex views, but we knew that a user generally opened just one of them. In that case we might provide an empty

div

for each of those views and fill out the ones the user chooses to visit. Instead of sending the html for an entire

div

each time one of them needs to be updated, however, we might check if the

div

is empty and only send the html the first time. Subsequent updates could then use jQuery.ajax() to get a JSON string containing just the data necessary to update the controls in the

div

. That would minimize the initial page size and provide the most efficient updates, giving the user the experience you want them to have when visiting the site.

Summary

This article showed how easy it is to change the way an ASP.NET web application requests data and updates controls in order to increase the responsiveness a site. The simple example reduced the postback size from 5.6 KB to just 501 bytes. A more complex application would likely see even larger decreases. If you’re familiar with developing ASP.NET web apps you can use the jQuery.ajax() methods demonstrated in this article to significantly improve the performance of new and existing sites while retaining the technologies you’re familiar with.

Calling aspx page method using jquery
Calling aspx page method using jquery

Partial Postback using UpdatePanel

The ASP.NET UpdatePanel control allows the developer to limit a page refresh to just a portion of the page. For instance, a button and a GridView control might be wrapped in an UpdatePanel so that only those two controls are refreshed. The UpdatePanel page of the sample application shows how that is done.

Before using an UpdatePanel, a ScriptManager must be defined in the aspx file. That is done by placing the following code somewhere near the top of the controls within the tag:

Then, somewhere below the ScriptManager definition, the controls to be grouped are wrapped with an UpdatePanel:

The UpdatePanel page is identical to the FullPostback page, except that the Load Users button and the two GridView controls are wrapped in an UpdatePanel.

The image above on the left shows that clicking the Load Users button results in a partial postback of 2.4 KB, as shown below.

The image above on the right shows that clicking a row in the Users GridView control results in a partial postback of 3.6 KB, as shown below.

So, for this example application, using an UpdatePanel reduced the data transfer when clicking a row in the Users GridView by 5.6 – 3.6 = 2.0 KB. In an actual application you would probably have more controls on the page that would be outside of the UpdatePanel, and the data associated with those controls would not be included in the partial postback. If that were the case, the difference between a full and partial postback would be greater. There is still, however, much more data being transferred than is necessary.

ASP.NET controls and not eliminated by the use of UpdatePanel. That data is passed as part of the postback, and contributes significantly to the size of the data being transferred. For instance, clicking on a user in the GridView results in the server sending the user details, along with the following ViewState data:

/wEPDwULLTEwNTc4OTU4OTAPZBYCAgMPZBYCAgMPZBYCZg9kFgQCAw8WAh4HVmlzaWJsZWcWAgIBDzwrABECAA8WBB4LXyFEYXRhQm 91bmRnHgtfIUl0ZW1Db3VudAIDZAwUKwAEFggeBE5hbWUFAklEHgpJc1JlYWRPbmx5aB4EVHlwZRkrAh4JRGF0YUZpZWxkBQJJRBYI HwMFCFVzZXJuYW1lHwRoHwUZKwIfBgUIVXNlcm5hbWUWCB8DBQpGaXJzdCBOYW1lHwRoHwUZKwIfBgUKRmlyc3QgTmFtZRYIHwMFCU xhc3QgTmFtZR8EaB8FGSsCHwYFCUxhc3QgTmFtZRYCZg9kFgpmD2QWAgIBDw8WAh8AaGRkAgEPZBYIAgEPDxYEHgRUZXh0BQExHwBo ZGQCAg8PFgIfBwUGc3NtaXRoZGQCAw8PFgIfBwUDU2FtZGQCBA8PFgIfBwUFU21pdGhkZAICD2QWCAIBDw8WBB8HBQEyHwBoZGQCAg 8PFgIfBwUGYmJyb3duZGQCAw8PFgIfBwUEQmlsbGRkAgQPDxYCHwcFBUJyb3duZGQCAw9kFggCAQ8PFgQfBwUBMx8AaGRkAgIPDxYC HwcFBGFhbnRkZAIDDw8WAh8HBQRBZGFtZGQCBA8PFgIfBwUDQW50ZGQCBA8PFgIfAGhkZAIFD2QWAgIBDzwrABEAZBgCBRNncmlkVm lld1VzZXJEZXRhaWxzD2dkBQ1ncmlkVmlld1VzZXJzDzwrAAwBCAIBZAd3OCiJnsqdo26ouHYmjru5jJEt9aENO9MlA6XK8Gao

We might be able to disable ViewState for some of the controls, but not all. If, instead, we use jQuery.ajax(), the only data that is transferred when clicking on the Users GridView would be the data associated with the user. The next section shows how to implement this technique.

public void GetArtikelByNavisionID()
{
string CS = ConfigurationManager.ConnectionStrings[“LagerLogistikConnectionString”].ToString();
using (SqlConnection connection = new SqlConnection(CS))
{
connection.Open();
SqlCommand command = new SqlCommand(“Here is the Query for example select Id =@Id”, connection);
command.Parameters.AddWithValue(“Id “, TextSearch.Text);
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
GridArtikel_Information.DataSource = dt;
GridArtikel_Information.DataBind();
}
}

var

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

This article presents an example of how to consume a web service in an ASP.NET application using the jQuery.ajax() method. I have been developing applications running on web browsers for many years and I realize that AJAX and jQuery are getting close to the ultimate dreams of any programmer working on this subject for some time. jQuery is a client-side scripting library, so it is totally independent from the development environment, regardless of whether it is ASP.NET, J2EE, PHP, or any other platform. Visual Studio is readily available to me, so the example is created as an ASP.NET project.

  • type: Specifies the type of request (GET or POST).
  • url: Specifies the URL to send the request to. The default is the current page.
  • contentType: The content type used when sending data to the server. The default is “application/x-www-form-urlencoded”.
  • dataType: The data type expected of the server response.
  • data: Specifies data to be sent to the server.
  • success(result,status,xhr): A function to be run when the request succeeds.
  • error(xhr,status,error): A function to run if the request fails.
  1. $.ajax({name:value, name:value, … }) //The parameters specifies one or more name/value pairs for the AJAX request.

Code

In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius and vice versa. The structure of the attached Microsoft Visual Studio 2012 solution is as follows:

This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services. Here in the TempratureConverter .asmx Web Service I wrote two web methods for a sample application. One is FahrenheitToCelsius() that will convert the temperature from Fahrenheit to Celsius and another one is CelsiusToFahrenheit that will convert the temperature from Celsius to Fahrenheit.

Note : To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line [System.Web.Script.Services.ScriptService].

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Services;
  6. namespace jQuery.AjaxWebServiceCall
  7. [WebService(Namespace = “http://tempuri.org/”)]
  8. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  9. [System.ComponentModel.ToolboxItem(false)]
  10. [System.Web.Script.Services.ScriptService]
  11. public class TempratureConverter : System.Web.Services.WebService
  12. [WebMethod]
  13. public string FahrenheitToCelsius(string fahrenheit)
  14. return (((Convert.ToDouble(fahrenheit) – 32) / 9) * 5).ToString();
  15. [WebMethod]
  16. public string CelsiusToFahrenheit(string celsius)
  17. return (((Convert.ToDouble(celsius) * 9) / 5) + 32).ToString();

This document is saved as an

.aspx

file. In the HTML section of

Default.aspx

, you can see that we only have a few functional visual components.

  1. <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”jQuery.AjaxWebServiceCall._Default” %>

This code shows how to call Web Service methods using a jQuery.ajax call. Here I am calling the Web Method on the TextBox Keyup event so as soon as the user enters data into the TextBox the keyup event is fired and due to the ajax call the result value will be displayed on the page.

You can easily debug jQuery.ajax calls using Firebug in Firefox or Developer Tools in Internet Explorer. You can see the parameters being sent to the Web Service using the ajax call and the response from the Web Service and the time period between the request and the response.

References

This article gives you step by step example for implementing Page Method and calling it through jQuery.ajax() call.

This example will read data from Customer table of Northwind database. You can download the Northwind database here. Depending on the selected Country value of DropDown, Customer details will be rendered if jQuery.ajax() call returns success.

jQuery library functions and methods have capabilities to load data from the server without a browser page refresh. jQuery.Ajax() performs an asynchronous HTTP request. This method can handle the response type of XML, JSON, script, or HTML. If you are making a request to other domain datatype jsonp should be used. You can perform asynchronously GET, POST, PUT or DELETE methods on the server using jQuery.Ajax().

Create new solution of ASP.NET. Open visual studio click on File -> New -> Project -> ASP.NET Web Application name it as jQueryAjax and click Ok.

Open Default.aspx or create new page with name Customer.aspx. In this step, we will add a DropDownList control to give users to select particular Country. You can also try with jQuery AutoComplete TextBox

We will also design a table object which will display Customer details on the selection of Country. The jQuery change event of DropDownList will be used to add rows to the table object.

Add below html in BodyContent ContentPlaceHolder of Default.aspx.


Country:
CustomerID CompanyName ContactName ContactTitle City Phone


Open Site.css from Styles folder and add below styles to it. These styles are applied to table, table header and table row objects.


.tblCustomers { font-family: verdana,arial,sans-serif; font-size:11px; color:#333333; border-width: 1px; border-color: #666666; border-collapse: collapse; } .customerth { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #dedede; } .customertd { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #ffffff; }

Add a new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will an get array of Customer object.

Add below properties to Customer.cs


public class Customer { public string CustomerID { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string City { get; set; } public string Phone { get; set; } }

Open codebehind file of Default.aspx page. Where we will add a PageMethod which takes Country as input parameter and return an array of Customer object.

It makes a database call to SQL Server and gets customer details depending on the provided country.

Add below code in Default.aspx.cs file. Notice that we have added [System.Web.Services.WebMethod] for GetCustomers method which allows access to methods by scripting method.


[System.Web.Services.WebMethod] public static Customer[] GetCustomers(string country) { List

customers = new List

(); string query = string.Format("SELECT [CustomerID], [CompanyName]," + " [ContactName], [ContactTitle]," + "[City], [Phone] FROM [Customers] " + "WHERE Country LIKE '%{0}%'", country); using (SqlConnection con = new SqlConnection("your connection string")) { using (SqlCommand cmd = new SqlCommand(query, con)) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Customer customer = new Customer(); customer.CustomerID = reader.GetString(0); customer.CompanyName = reader.GetString(1); customer.ContactName = reader.GetString(2); customer.ContactTitle = reader.GetString(3); customer.City = reader.GetString(4); customer.Phone = reader.GetString(5); customers.Add(customer); } } } return customers.ToArray(); }


In this step we will call PageMethod created in previous step. Create a new JavaScript file by open Solution Explorer -> right click on Scripts folder -> Select Add -> New Item -> Choose JScript -> Name it as Customer.js and click Ok

Add function for ddlCountry DropDownList’s change event. Whenever user change the selection of country, PageMethod will be called through jQuery.Ajax(). If the call is a successful it will read Customer details and add each customer as table row to tblCustomers.


$(document).ready(function () { $("#MainContent_ddlCountry").change(function () { $("#tblCustomers tbody tr").remove(); $.ajax({ type: "POST", url: "Default.aspx/GetCustomers", data: '{country: "' + $(this).val() + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { response($.map(data.d, function (item) { var rows = "

" + "

" + item.CustomerID + "

" + "

" + item.CompanyName + "

" + "

" + item.ContactName + "

" + "

" + item.ContactTitle + "

" + "

" + item.City + "

" + "

" + item.Phone + "

" +"

"; $('#tblCustomers tbody').append(rows); })) }, failure: function (response) { var r = jQuery.parseJSON(response.responseText); alert("Message: " + r.Message); alert("StackTrace: " + r.StackTrace); alert("ExceptionType: " + r.ExceptionType); } }); }); });

$(“#tblCustomers tbody tr”).remove(); removes existing rows from table object.

Url is mentioned as “Default.aspx/GetCustomers” which indicates where your PageMethod exists.

PageMethod takes country as input parameter which is mentioned with data property of $.ajax.

success: function (data) { } will execute when PageMethod executes successfully. It add row for each customer record.

failure: function (response) { } will execute if there is any error in execution of PageMethod and gives details of error.

Open Site.Master file and add a reference to the script file in head tag of Master page.

Your head tag will look like this

I am having a default.js file in shared folder. Dynamically we will send aspx file name and function name and the parameters to call corresponding aspx page and method.


Default.js method
function ValidateParams(fromdate,Id)
{
var exp=/^((((0?[13578])|(1[02]))[\/]((0?[1-9]|[0-2][0-9])|(3[01])))|(((0?[469])|(11))[\/]((0?[1-9]|[0-2][0-9])|(30)))|(0?[2][\/](0?[1-9]|[0-2][0-9])))[\/]\d{4}$/;
var exp1=/^(\d{9})$/;
if(exp.test(fromdate)&& exp1.test(Id))
{
CheckValidityofId("FormUI.CheckValidity",fromdate,Id)
}
}
function CheckValidityofId(lookupFunction,fromdate,Id) {
callback = function(response) {
if (response.error) {
alert(response.error);
}
else {
if (response.value =="NotAssociated")
{
document.getElementById(MessageID).innerText="Number is not associated";
}
else
{
document.getElementById(MessageID).innerText="This is NOT eligible";
}
}
}
if (fromdate.length > 0 && Id.length >0) {
eval(lookupFunction + "('" + fromdate + "','" + Id "'," + callback + ")");
}
return false;
}


Here is my FormUI.ascx.cs method
public partial class FormUI : UIView
{
[Ajax.AjaxMethod()]
public string CheckValidity(string FromDate, string Id)
{
// logic goes here
}
}


Please correct me what's the wrong why the above code is not working. Its not hitting the 'CheckValidity' method in ascx.cs file. Even I tried with the below code but its's also not working
Please let me know what is missing.

This is asked many times on asp.net forums,

1. How to call Server Side methods or functions using JavaScript in ASP.Net

2. How to call Server Side methods Client Side in ASP.Net

Now the answer is using jQuery.

jQuery allows you to call Server Side ASP.net methods from client side without any PostBack. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.

Syntax

The
following picture describes the syntax of the jQuery AJAX call.

HTML Markup

The
following HTML Markup consists of an ASP.Net TextBox and an HTML Button.

Your Name :

onclick = “ShowCurrentTime()” />

Client Side
Script

When the Button is clicked the ShowCurrentTime JavaScript function is executed which makes an AJAX call to the
GetCurrentTime WebMethod. The value of the TextBox is passed as parameter to the WebMethod.

The WebMethod

The
following WebMethod returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) and Shared
(VB.Net) and is decorated with WebMethod attribute, this is necessary
otherwise the method will not be called from client side jQuery AJAX call.

C#

[System.Web.Services.WebMethod]

public static string GetCurrentTime(string name)

return “Hello ” + name + Environment.NewLine + “The Current Time is: ”

+ DateTime.Now.ToString();

VB.Net

Public Shared Function GetCurrentTime(ByVal name As String) As String

Return “Hello ” & name & Environment.NewLine & “The Current Time is: ” & _

DateTime.Now.ToString()

End Function

Screenshot

Browser Compatibility

The
above code has been tested in the following browsers.

* All
browser logos displayed above are property of their respective owners.

Demo

View Demo

Downloads

Download Code

Featured

How to use AJAX with ASP.NET Webform

Last modified: February 25, 2022

Step 1

Create an ASP.NET Web Form application.

Step 2

Delete the content of the Default.aspx and we left with below.


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAX._Default" %>

Step 3

RouteConfig.cs file in the App_Start folder, we need to modify the file. For RegisterRoutes, we need to replace with the following code otherwise the AJAX will return 401.


public static void RegisterRoutes(RouteCollection routes) { var settings = new FriendlyUrlSettings(); settings.AutoRedirectMode = RedirectMode.Off; routes.EnableFriendlyUrls(settings); }

In AJAX call, we have couple of HTTPMost common are below.
  • GET – equals to get the data from server
  • POST – equals to sending the data to server to insert
  • PUT – equals to sending the data to server to update
  • DELETE- equals to sending the data to server to delete

It is very import that we put [WebMethod] on top of method, otherwise we can’t call in AJAX.

Create a class called Mobile with below properties


public class Mobile { public string ModelName { get; set; } public decimal Price { get; set; } }

Step 4 GET


[WebMethod] [ScriptMethod(UseHttpGet = true)] public static List

GetMobileList() { var mobileList = new List

() { new Mobile{ModelName= "Iphone12", Price = 600}, new Mobile{ModelName= "Iphone12Pro", Price = 700}, new Mobile{ModelName= "Iphone13", Price = 800}, new Mobile{ModelName= "Iphone13Pro", Price = 900}, new Mobile{ModelName= "Iphone12", Price = 1000}, }; return mobileList; }


Step 5 POST


[WebMethod] // POST public static string SayHello(string name) { return "Hello " + name; }

Step 6 PUT
Step 7 DELETE

Both PUT and DELETE in ASP.NET Webform use POST Verbs

Step 5

We create a button to trigger the AJAX call when it is click. We are using JQuery AJAX methods.

  • type: type of verb of the method e.g. POST, GET
  • url: the endpoint of the method to call
  • data: the date to send from User Interface to Code Behind method
  • contentType: type of content format we are sending
  • dataType: type of conent when receiving

We need to use msg.d to get the message.





Name

Price

Make AJAX Call to ASP.Net Server Side Web service method using jQuery with C#
Make AJAX Call to ASP.Net Server Side Web service method using jQuery with C#

Full Postback

Every click on a control in an ASP.NET page will result in a full postback of the entire page if nothing has been done to optimize those actions. This might result in a very large amount of data being transferred from the server to the client on every click. For instance, the examples that accompany this article have a page containing two GridView controls, with the second one containing details of the selected row of the first. Clicking a row in the first GridView results in new data being retrieved for the second GridView. Clicking a row will result in a full postback, including the data for the first GridView, even though that data did not change. This results in an unnecessary amount of data transfer. Ideally, just the page data that is changed should be transferred.

The sample application for this article has a FullPostback page that demonstrates this. The size of the data transfer is shown in the Developer Tools section at the bottom of each image shown below. (You can open Developer Tools in the Chrome browser by clicking F12.)

The image above on the left shows that clicking the Load Users button results in a full postback of 4.5 KB (3.2 KB for the page and 1.3 KB for the stylesheet, as shown below).

The image above on the right shows that clicking a row in the Users GridView control results in a full postback of 5.6 KB (4.3 KB for the page and 1.3 KB for the stylesheet, as shown below).

The difference in size between the page with no user selected and a user selected is 4.3 – 3.2 = 1.1 KB. Assuming that 1.1 KB is the size of the data in the User Details table, it would be better if just that amount of data would be transferred when a user clicks on the Users GridView. A common way to reduce that size is to use the ASP.NET UpdatePanel control to refresh just the portion of the screen that changes. The next section shows how that is done.

jQuery Ajax in ASP.NET

The following are asked many times on ASP.NET forums:

  1. How to call server-side methods or functions using JavaScript in ASP.NET
  2. How to call server-side methods client-side in ASP.NET

The answer is to use jQuery.

jQuery allows you to call server-side ASP.NET methods from the client-side without any PostBack. Actually, it is an AJAX call to the server but it allows us to call the method or function defined server-side.

The figure below describes the syntax of the call.

  1. $.ajax({
  2. type: “POST”,
  3. url: “CS.aspx/MethodName”,
  4. data: ‘{name: “‘ + $(“#<%=txtUserName.ClientID%>”)[0].value + ‘” }’,
  5. contentType: “application/json; charset=utf-8”,
  6. dataType: “json”,
  7. success: OnSuccess,
  8. failure: function(response) {
  9. alert(response.d);
  10. });

HTML Markup

  1. Your Name :

As you can see in the preceding I have added a TextBox when the user enters his name and a TML button that calls a JavaScript method to get the Current Time.

Client-side Methods

The ShowCurrentTime method above makes an AJAX call to the server and executes the GetCurrentTime method that accepts the username and returns a string value.

Server-Side Methods

C#

  1. [System.Web.Services.WebMethod]
  2. public static string GetCurrentTime(string name)
  3. return “Hello ” + name + Environment.NewLine + “The Current Time is: ” +
  4. DateTime.Now.ToString();

VB.Net

  1. Public Shared Function GetCurrentTime(ByVal name As String) As String
  2. Return “Hello ” & name & Environment.NewLine & “The Current Time is: ” & _
  3. DateTime.Now.ToString()
  4. End Function

The preceding method simply returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) or Shared (VB.Net) and also it is declared as a Web Method since unless you do this you won’t be able to call the methods.

ASP.NET MVC -  #28: Cách gọi AJAX trong ASP.NET MVC | AJAX call in ASP.NET MVC | TEDU
ASP.NET MVC – #28: Cách gọi AJAX trong ASP.NET MVC | AJAX call in ASP.NET MVC | TEDU

Keywords searched by users: ajax call in aspx page

Calling Aspx Page Method Using Jquery - Youtube
Calling Aspx Page Method Using Jquery – Youtube
Hajan Selmani - Ajax-Based Data Loading Using Jquery.Load() Function In  Asp.Net
Hajan Selmani – Ajax-Based Data Loading Using Jquery.Load() Function In Asp.Net
Hajan Selmani - Ajax-Based Data Loading Using Jquery.Load() Function In  Asp.Net
Hajan Selmani – Ajax-Based Data Loading Using Jquery.Load() Function In Asp.Net
Make Ajax Call To Asp.Net Server Side Web Service Method Using Jquery With  Vb.Net - Youtube
Make Ajax Call To Asp.Net Server Side Web Service Method Using Jquery With Vb.Net – Youtube
Github - Geeksarray/Jquery-Ajax-Call-With-Jsonresult-In-Asp-Net-Mvc: This  Article Gives You Details About How You Can Implement Jquery Ajax Calls To  Asp.Net Mvc Controller And Display Jsonresult On View.
Github – Geeksarray/Jquery-Ajax-Call-With-Jsonresult-In-Asp-Net-Mvc: This Article Gives You Details About How You Can Implement Jquery Ajax Calls To Asp.Net Mvc Controller And Display Jsonresult On View.
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
Jquery Ajax Json Example In Asp.Net To Insert Data Into Sql Server Database  Without Postback ~ Asp.Net,C#.Net,Vb.Net,Mvc,Jquery,Javascipt,Ajax,Wcf,Sql  Server Example
Jquery Ajax Json Example In Asp.Net To Insert Data Into Sql Server Database Without Postback ~ Asp.Net,C#.Net,Vb.Net,Mvc,Jquery,Javascipt,Ajax,Wcf,Sql Server Example
Call Asp.Net Webservice Using Jquery With Parameters
Call Asp.Net Webservice Using Jquery With Parameters
Displaying A Progress Indicator During Jquery Ajax Calls | Binaryintellect  Knowledge Base
Displaying A Progress Indicator During Jquery Ajax Calls | Binaryintellect Knowledge Base
Post Form Data To Controller In Asp.Net Mvc Using Ajax - Dotnetxp
Post Form Data To Controller In Asp.Net Mvc Using Ajax – Dotnetxp
Calling Asp Net Web Services Using Jquery Ajax - Youtube
Calling Asp Net Web Services Using Jquery Ajax – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *