Monday, April 1, 2019

Create a web method in c# asp.net.

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>

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:



Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...