Alternate way to use page method inside user contr

2019-02-18 04:30发布

问题:

Is there a way by which i can achieve functionality of page method inside a user control.

Any help is appreciated, Thanks :)

回答1:

The easiest way is probably to put the functionality you want in a webservice then use the scriptservice attribute to make that available.

Works very similarly to a page method.

Quite an extensive example here.

        <asp:ScriptManager>
            <Services>
                <asp:ServiceReference Path="~/MyWs.asmx" />
            </Services>
        </asp:ScriptManager>

Then you can call your webmethods in JS: MyNamespace.MyWs.MyMethod();



回答2:

What works for me is to put my WebMethods in a custom class that is derived from System.Web.UI.Page

public class MyPage : System.Web.UI.Page
{
    [WebMethod]
    public static bool MyMethod(string value)
    {
        return true;
    }
}

Then whenever I have a page containing a usercontrol that needs to consume that WebMethod, I derive that page from my custom page class instead of System.Web.UI.Page.