Monday, June 9, 2014

Call ASP.NET Code behind function without parameter from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the RunMe function is called from client side when we click the Button1. The c# function should be static and decorated using [WebMethod] attribute. Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <title></title>
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  5. <script type="text/javascript">
  6. $(document).ready(function ()
  7. {
  8. $("#Button1").click(function ()
  9. {
  10. $.ajax({
  11. type: "POST",
  12. url: "Default.aspx/RunMe", // Your page and function name
  13. dataType: "json",
  14. contentType: "application/json; charset=utf-8",
  15. success: function (res)
  16. {
  17. //will return null
  18. console.log(res);
  19. },
  20. failure: function (response)
  21. {
  22. console.log(response.d);
  23. }
  24. });
  25. });
  26. });
  27. </script>
  28. </head>
  29. <body>
  30. <form id="form1" runat="server">
  31. <div>
  32. <input id="Button1" type="button" value="button" />
  33. </div>
  34. </form>
  35. </body>
  36. </html>

Namespace:

  1. using System.Web.Services;

Code behind C#:

  1. [WebMethod]
  2. public static void RunMe()
  3. {
  4. //Write whatever you neeed..
  5. }

No comments:

Post a Comment