0

I have a public method in my content page class, I want to call this method from master page class.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
  • If you do cphAdmin.Page as BasePage, it won't throw a NullReferenceException if the cast is unsuccessful. It will silently return null. So you'll actually have to do - BasePage page = cphAdmin.Page as BasePage); if (null != page) . The direct cast operator will throw a NullReferenceException if the cast is unsuccessful. – Kirtan May 22 '09 at 10:46
  • You can also take a look at this - http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/ – Kirtan May 22 '09 at 10:49

3 Answers3

7

You can inherit your page from a base class. Then you can create a virtual method in your base class which will get overridden in your page. You can then call that virtual method from the master page like this -

(cphPage.Page as PageBase).YourMethod();

Here, cphPage is the ID of the ContentPlaceHolder in your master page. PageBase is the base class containing the YourMethod method.

EDIT: Of course, you'll have to put a null checking before you call the YourMethod method using the page's instance.

Kirtan
  • 21,295
  • 6
  • 46
  • 61
  • Excellant Idea! I already have a base class that is inherited by page, so immediate the problem is solved. – Muhammad Akhtar May 20 '09 at 10:51
  • Can you plz tell me what's the difference b/w both statement or these are same (cphAdmin.Page as BasePage).yourmethod(); BasePage bp = (BasePage)cphAdmin.Page; bp.yourmethod(); – Muhammad Akhtar May 22 '09 at 07:46
3

if you do not want to use any base page

add this to your master page,

private object callContentFunction(string methodName, params object[] parameters)
{
    Type contentType = this.Page.GetType();
    System.Reflection.MethodInfo mi = contentType.GetMethod(methodName);
    if(mi == null)return null;
    return mi.Invoke(this.Page, parameters);
}

then use it

callContentFunction("myPublicMethodName", myParam1, myParam2...);

Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28
  • Reflection must be minimally used in an ASP.NET application especially in the presentation layer. And method invocation is one of the most unoptimized operation of Reflection. – Kirtan May 20 '09 at 11:02
  • "Reflection must be minimally used in an ASP.NET" why? – Tolgahan Albayrak May 20 '09 at 11:05
2

STEPS:

  1. Add New <%@ MasterType VirtualPath="location of your masterpage" %> directive to .aspx page

  2. Declare one public function in MasterPage.

  3. Call the function from content page using Master.functionName().

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343