Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi all,
I want calling page methods from javascript. how to call pagemethods with loading page.
Posted
Comments
I.explore.code 17-Oct-12 5:36am    
using jQuery AJAX! and you would have to mark those methods with [ScriptMethod] attribute!

you need to make your page method like this...
make sure it will static with public identifier.
C#
[WebMethod]
public static void YouPageMethod()
{

}




and if you want to call that method on your page load event then you need to call it like this....

XML
<script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/YouPageMethod",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert('Method Called Sucess fully');
                },
                error: function (result) {
                    alert("error " + result);
                }
            });
        });
    </script>



if you need to pass parameter to your method then use data like this, but one thing parameter name is same as your method parameter name.
JavaScript
data:"{ParamterName:'VALUE',ParamterName2:'Value'}",


but one more thing you can not access your form control like grid or text box in side your web method as it is static.
 
Share this answer
 
v3
Just some more information is need to add

If you write web method inside any aspx.cs file then the web method should be static

C#
[WebMethod]
public static void YouPageMethod()
{

}


any when call your web method from your javascript then the script need to add that aspx file. If you call a web method from one markup/page and actual webMethod is exists to another page then it will not work. If you want to share web method from multiple page then the web method should be declare to the base page.

C#
public abstract class PageBase:Page
{
   [WebMethod]
   public static void YouPageMethod()
   {

   } 
}

public partical class MyDerivedPage:PageBase
{

}

$(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "MyDerivedPage.aspx/YouPageMethod",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert('Method Called Sucess fully');
                },
                error: function (result) {
                    alert("error " + result);
                }
            });
        });
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900