Wednesday, March 21, 2012

Define a PageMethod in a MasterPage

I have a web site that uses Master/Content pages and I have a PageMethod that I would like to make available to a any of the content pages. So I defined the method like I would in a Content Page:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Text;

using System.Web;

using System.Web.Security;

using System.Web.Services;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Web.Configuration;

publicpartialclassMasterPage : System.Web.UI.MasterPage

{

[WebMethod]

publicstaticstring MyMethod()

{

//Some Code Here

}

}

And I already have my script manager setup on the master page as follows, which works for all my PageMethod calls from Content Pages:

<asp:ScriptManagerID="masterPageScriptManager"runat="server"EnablePageMethods="true"EnablePartialRendering="true">

</asp:ScriptManager>

However, when I try to call PageMethods.MyMethod(MyMethodCompleteHandler); I get our favorite error, "PageMethods is Undefined." Is it possible to define a PageMethod in a MasterPage like this. If so what am I missing?

Thanks

Patrick

To be able to invoke that MyMethod

you need first to cast the MasterPage property of a page to your class (MasterPage) and then invoke it.

So if it was in the code behind of a content page to be able to invoke it you should write sth like :

string result = ((MasterPage)this.MasterPage).MyMethod();



Yani, I think he's talking about fromt eh javascript side.

On an unrelated note, mnogo mi obicham Bulgaria! Moja jena e bulgarka i nia otidame tam v sofia za 2-3 cedmitsi prez ljatoto vseki godina.

Paul (my apologies for grammar and spelling)


Hi Paul,

you are right about the javascript.

However, my point was that defined on the master page this static method does not become a page (content page) method. The master page is not a base class for the content pages, moreover it is a static page.

For this case it would be more suitable to create a web service, that will be accessible from everywhere.

Cheers,

Yani

PS: Paul, it is very nice you have learn some Bulgarian :)) Congrats!Wink


To answer the original question, I looked at the response in Fiddler and it looks like the Master page pagemethod doesn't get generated. I'm not yet sure how to work around that, I'll give it some thought.

Patrick,

I believe you won't be able to accomplish what you're trying with PageMethods.

The EnablePageMethods will assume that the method is defined in a.aspx page. This is why it is called a "Page Method".

If you want the method be available to all pages, why not use a simple webservice?

No comments:

Post a Comment