25 May 2009

ASP.NET How To access Master Page Variables Class Members C#.NET

Sometimes we need to access to a variable in master page file.
For example I need to change the body onload event in html.

In the asp.net file, we simply cast our master page as its class name.

in master page aspx we add the code below.

<body onload="<%=myloadstr %>" >

in master page cs code we add the code below.
we declare it as public to access the variable.

public string myloadstr = "";

And add the code below in your asp.net cs source file.

((myMasterPage)this.Master).myloadstr = "here some javascript for load";

myMasterPage is the name of my masterpage class. We cast our asp.net page its masterpage, with "this.Master".


Anonymous said...

Gosh, I love your provided options {helpful|interesting|cool} ...all positive? lol

Anonymous said...

what a great solution such its realy helpfull to me thanks a lot !!

Anonymous said...

Such a great solution! Clean, simple, and effective, thank you!

Femi said...

Excellent solution, but doesnt work on page without code behind for some reason.

Femi said...

for non code behind pages delare
<%@ MasterType TypeName='MasterPage' VirtualPath="~/MasterPage.master" %>

If you need this to work.

Alternatively if the master page class is delared as unique name.

e.g. public partial class _MasterPage : System.Web.UI.MasterPage

accessibility will be through _MasterPage.variables

Anonymous said...

ideal fo db connection object...