This article explains how to call a Server Side method from JavaScript in ASP.NET C#.

The following is my aspx code.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Java Script: Calling Server Side Method</title>
  6. <script type="text/javascript" language="javascript">
  7. function jsCallServerSideMethod() {
  8. var _msg = $get("txtMessage").value;
  9. PageMethods.GetUserMessage(_msg, OnSuccess, OnFailure);
  10. }
  11. function OnSuccess(result) {
  12. if (result) {
  13. alert(result);
  14. }
  15. }
  16. function OnFailure(error) {
  17. }
  18. </script>
  19. </head>
  20. <body>
  21. <form id="form1" runat="server">
  22. <div>
  23. <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
  24. </asp:ScriptManager>
  25. <table style="border: solid 15px blue; width: 100%; vertical-align: central;" cellpadding="10"
  26. cellspacing="10">
  27. <tr>
  28. <td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; background-color: skyblue;
  29. font-family: 'Times New Roman'; font-size: 20pt; color: red;">
  30. Java Script: Calling Server Side Method
  31. </td>
  32. </tr>
  33. <tr>
  34. <td style="text-align: left; font-family: Times New Roman; font-size: 12pt;">
  35. Enter Your Message #
  36. <asp:TextBox ID="txtMessage" runat="server" Width="200px"></asp:TextBox>
  37. <asp:Button ID="btnClick" runat="server" Text="Click" OnClientClick="jsCallServerSideMethod()" />
  38. </td>
  39. </tr>
  40. </table>
  41. </div>
  42. </form>
  43. </body>
  44. </html>

The following is my aspx.cs code.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Web.Services;
  8. public partial class _Default : System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. }
  13. [WebMethod]
  14. public static string GetUserMessage(string message)
  15. {
  16. return "Welcome " + message + Environment.NewLine + System.DateTime.Now;
  17. }
  18. }

Now run the application.

javaScript
Image 1.

application
Image 2.

run the application
Image 3.