Steve C. Orr

Software Engineer, Web Developer, Database Designer
 
  

 

Q: How do I pass a value between an ASP.NET 2.0 page and its master page?

A: The routine for passing data around remains similar for new ASP.NET constructs, such as Master Pages. From the aspect of passing data around, the master page acts as a control within the page. So, as with the earlier page/control techniques, to call a public method located within a page’s master page, you must cast the master reference to the exact class name:

Dim MP As MyMasterPage

MP = CType(Me.Master, MyMasterPage)

MP.MyPublicMasterPageSub()

 

'The above 3 lines can alternatively be simplified to one:

CType(Me.Master, MyMasterPage).MyPublicMasterPageSub()

To pass data from the master page to the page, the master page should raise an event to the page:

Public Event MasterPageButtonClicked()

Then the event can be raised to the page with a single line of code:

RaiseEvent MasterPageButtonClicked()

The page can handle the event just as if it were coming from a user control:

Private WithEvents _MyMasterPage As MyMasterPage

Private Sub MyMasterPage_ButtonClicked() _

  Handles _MyMasterPage.ButtonClicked

  Response.Write("Master page raised button click event.")

End Sub

The only difference is that you need to assign the master page reference to the _MyMasterPage variable because ASP.NET (Beta 2) doesn’t do this for you:

MyMasterPage = CType(Me.Master, MyMasterPage)

That line of code could go in the Page_Load event — or nearly anywhere else that’s convenient.


 

(advertisement)