C# – Calling a Web Method from ASPX Code Behind

asp.netcwebmethod

I'm trying to figure out a way that I can call a Web Method (located as a public static method in the code behind of an aspx page) from another ASPX Code Behind page.

This is the code behind of Page A.aspx

public partial class PageA : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    // other code not relevant is here  
    }

    [WebMethod(true)]
    public static string GetStringInfo()
    {
         // do some stuff here to build my string
         // return string
    }
}

On page B, I need to be able to call GetStringInfo() during page load or some other event to get the information. the GetStringInfo() is fairly complex and for reasons outside of my control, can't be moved elsewhere or rebuilt presently.

How can I consume the web method above from another page's code behind?

I've tried instantiating a copy of the other page (PageB), such as:

public partial class PageB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       PageA page = new PageA();
       page.GetStringInfo();        
    }
}

The problem here is since it's dynamically compiled, I don't have an easy namespace to reference and access. I've tried adding one, and it ignores it.

This project is on .net 3.5, C#, and is a web site project (not a web application).

Any help is appreciated!

Best Answer

If the GetStringInfo method is static you don't need an instance of PageA to invoke it:

public partial class PageB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       string info = PageA.GetStringInfo();        
    }
}
Related Topic