In this article, i have explain how to create web method in c# and how to use it.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Web-Method.aspx.cs" Inherits="Tutorials.Web_Method" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
getCurrentDateAndTime();
function getCurrentDateAndTime() {
$.ajax({
type: "POST",
url: "Web-Method.aspx/getCurrentDateAndTime",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
alert(response.d);
$("#currentDate").html(response.d);
},
failure: function (response) {
alert(response.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="currentDate">
</div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Web-Method.aspx.cs" Inherits="Tutorials.Web_Method" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
getCurrentDateAndTime();
function getCurrentDateAndTime() {
$.ajax({
type: "POST",
url: "Web-Method.aspx/getCurrentDateAndTime",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
alert(response.d);
$("#currentDate").html(response.d);
},
failure: function (response) {
alert(response.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="currentDate">
</div>
</form>
</body>
</html>
C# code
using System;
namespace Tutorials
{
public partial class Web_Method : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string getCurrentDateAndTime()
{
return " Current Date "+ System.DateTime.Now ;
}
}
}
Output: