This article explains how to call a Server Side method from JavaScript in ASP.NET C#.
The following is my 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>
-
- <script type="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>
- <form id="form1" runat="server">
- <div>
- <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
- </asp:ScriptManager>
- <table style="border: solid 15px blue; width: 100%; vertical-align: central;" cellpadding="10"
- cellspacing="10">
- <tr>
- <td style="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>
- <td style="text-align: left; font-family: Times New Roman; font-size: 12pt;">
- Enter Your Message #
- <asp:TextBox ID="txtMessage" runat="server" Width="200px"></asp:TextBox>
- <asp:Button ID="btnClick" runat="server" Text="Click" OnClientClick="jsCallServerSideMethod()" />
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
The following is my aspx.cs code.
- 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
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
-
- [WebMethod]
- public static string GetUserMessage(string message)
- {
- return "Welcome " + message + Environment.NewLine + System.DateTime.Now;
- }
- }
Now run the application.
Image 1.
Image 2.
Image 3.