Wednesday, April 8, 2009

How to call asp.net page method from javascript using scriptmanager

In Asp.Net 3.5 you can call any method of your .aspx page By Javascript Function..
    
    this is possible because new feature ScriptService in asp.net.
    
    To call page method from javascript:
    
    (1)methos should be declared as Public and Static
    (2)[WebMethod] attribute must be attached with methos.   
    (3)At least One ScriptManager Should be on Page.
    (4)Set EnablePageMethods of ScriptManager to "true" 
    
    once you complete this steps.
    Here is the server side methos looks like:
    
    [WebMethod]
    public static string GetName(string Name)
    {
        return "Hello " + Name + "!!!";
    }
    
    now you have to write function in javascript that notify whether method call was successfull or failed.
    
    function onSuccess(data)
    {
        alert(data);
    }
    function onFail(error)
    {
        alert("Failed");
    }
    
    After Writing this You can Call GetName method of your asp.net Page like:    
    
    PageMethods.GetName("http://dhameliya.blogspot.com",onSuccess,onFail,null);    
     
    here  first parameter is argument,second one is Success Callback and third one is Failure Callbak..
    
    Hope this will will help you .
    Thanks..