Java Script – Call a Server Side Method in ASP.NET CSharp with example

  ASP.NET Snippets

Java Script – Call a Server Side Method in ASP.NET C Sharp with example

Below is Default.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Java Script: Calling Server Side Method</title>

    <scripttype="text/javascript"language="javascript">
        function jsCallServerSideMethod() {
            var _msg = $get("txtMessage").value;
            PageMethods.GetUserMessage(_msg, OnSuccess, OnFailure);
        }
        function OnSuccess(result) {
            if (result) {
                alert(result);
            }
       }
        function OnFailure(error) {
        }
    </script>
</head>
<body>
    <formid="form1"runat="server">
    <div>
        <asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="True">
        </asp:ScriptManager>
        <tablestyle="border: solid 15px blue; width: 100%; vertical-align: central;"cellpadding="10"
            cellspacing="10">
            <tr>
                <tdstyle="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; background-color: skyblue;
                    font-family: 'Times New Roman'; font-size: 20pt; color: red;">
                    Java Script: Calling Server Side Method
                </td>
            </tr>
            <tr>
                <tdstyle="text-align: left; font-family: Times New Roman; font-size: 12pt;">
                    Enter Your Message #
                    <asp:TextBoxID="txtMessage"runat="server"Width="200px"></asp:TextBox>
                    <asp:ButtonID="btnClick"runat="server"Text="Click"OnClientClick="jsCallServerSideMethod()"/>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Write the following codes in code behind:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
    protectedvoid Page_Load(object sender, EventArgs e)
    {
    }
    [WebMethod]
    publicstaticstring GetUserMessage(string message)
    {
        return"Welcome " + message + Environment.NewLine + System.DateTime.Now;
    }
}

So, We learned how to do, Java Script – Call a Server Side Method in ASP.NET CSharp with example