Sunday, 22 April 2012

call asp.net page methods from javascript


 Mark your method as static and give it the WebMethod attribute
The method has to be declared static. It must also be marked with the WebMethod attribute. You'll probably find that you need to include System.Web.Services
using System.Web.Services;
[WebMethod]
public static string MyMethod(string name)
{
    return "Hello " + name;
}

Client Side


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._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 id="Head1" runat="server">
    <title></title>
  
     <script language="javascript" type="text/javascript">
         function OnRequestComplete(result, userContext, methodName) {
             alert(result);

         }
         function OnRequestError(error, userContext, methodName) {
             if (error != null) {
                 alert(error.get_message());
             }
         }
         function SubmitData() {

             PageMethods. MyMethod ("Test",OnRequestComplete, OnRequestError);
         }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
      <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
       <input type="button" value="Submit" onclick="SubmitData()" />
    </div>
    </form>
</body>
</html>


Mark your method as static  and EnablePageMethods=true are very important.

If you miss static keyword, it will show error like "Microsoft JScript runtime error : Page method is undefined"


Call Server Side function using jquery

  [WebMethod]
    public static string DisplayData(string name,int id)
    {
        return "name:" + name  + " Id: " + id;
    }

Client side


<!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 id="Head1" runat="server">
<title>JQuery Call asp.net page methods</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Default.aspx/DisplayData",
            data: '{"name":"test","id":"1"}',
            dataType: "json",
            success: function (data) {
                $("#lbltxt").text(data.d);
            },
            error: function (result) {
                alert("Error");
            }
        });
    });
</script>
</head>
<body>
<form id="form1" runat="server">
<label id="lbltxt" runat="server"></label>
</form>
</body>
</html>





No comments:

Post a Comment