How to call Backend Method Using Ajax without loading a page in asp dot net ?
ASP.NET Web Forms application, you can use AJAX (Asynchronous JavaScript and XML) to call backend methods without reloading the entire page.
This is useful for creating a more responsive and dynamic user experience.
Let's understand how Ajax is work ?
Example: Create a Webform :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
function callBackendMethod() {
$.ajax({
type: "POST",
url: "Test.aspx/HelloWorld",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#lblMessage').text(response.d);
},
failure: function (response) {
alert('Failed to call backend method.');
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnCallMethod" runat="server" Text="Call Backend Method" OnClientClick="callBackendMethod(); return false;" />
<br /><br />
<asp:Label ID="lblMessage" runat="server" Text="Message will appear here"></asp:Label>
</div>
</form>
</body>
</html>
Code-Behind Static Method:
using System;
using System.Web.Services;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string HelloWorld()
{
return "Hello, this is a message from the backend!";
}
}
[WebMethod]
attribute is used to expose the method as a web service method, allowing it to be called via AJAX.static
so that it can be called without an instance of the page.