When in the page lifecycle we can assign master page? - c#

I know ViewState is available between InitComplete and Preload events in LoadViewSate method. Similarly, I want to know in which page lifecycle event can we assign a master page for a particular page?

Because the master page and content page are merged during the
initialization stage of page processing, a master page must be
assigned before then. Typically, you assign a master page dynamically
during the PreInit stage
On Page PreInit event
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MyMaster.master";
}
Read Working with ASP.NET Master Pages Programmatically

From: ASP.NET Page Life Cycle Overview
Page Event
Typical Use
PreInit
Raised after the start stage is complete and before the initialization stage begins. Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property
values.
Note If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
From: Attaching Master Pages Dynamically
In addition to specifying a master page declaratively (in the # Page directive or in the configuration file), you can attach a master page dynamically to a content page. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then. Typically, you assign a master page dynamically during the PreInit stage, as in the following example:
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/DefaultMaster.master";
}
Edit:
Source: ASP.NET Master Pages - How Master Pages Work
You can use #Page directive also to specify master page.
<% # Page Language="C#" MasterPageFile="~/Master.master" Title="Content Page 1" %>

Related

Change label in masterpage in just one content page

How do I define a label in a masterpage from inside one control page, withouth losing it when I navigate to another control page? I know that I can use this code and it works:
(Master.FindControl("myControl") as Label).Text = "someNewContent";
But I have to define this on every page to keep the same content in the label. Is there a easier/shorter way to define this piece of code only one time in the whole program? Thanks in advance.
I think I get the gist of what you're asking:
Firstly, I would strongly type the master page, in your content page just below the #Page directive, by using the #MasterType directive:
<%# MasterType TypeName="*fully qualified type of your master page*" %>
Next, place a public property on your master page, like so:
public string MyText
{
set { this.ViewState["TheText"]; }
}
In your content page (during the Page_Init, for instance) you can add:
this.Master.MyText = "Whatever you want to say!";
Then load your master pages control text property in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
this.myControl.Text = Convert.ToString(this.ViewState["TheText"]);
}
This won't persist from content page to content page because each content page instantiates a new instance of the master page. In that case, put whatever text you want to persist in Session, then read it in the mater pages Page_Load event.
Hope this answers your question.

Session variable and Masterpages

I want to log a users session on my site. I was hoping to just set a session variable. But the initialisation of it is giving me problems.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["SESSION_GUID"] == null)
{
Session["SESSION_GUID"] = Guid.NewGuid().ToString();
Response.Redirect(Request.Url.ToString(), true);
return;
}
lnkUpload.Visible = (Session["LOGGED_IN"] != null);
btnLogout.Visible = (lnkUpload.Visible);
}
It seems that the masterpage is creating the variable OK, but the rest of the pages load (ones using that master page). So in my log, I am seeing TWO hits. One with no session ID set, and the second hit has a session id.
Any idea why the child page of this masterpage is loading twice? This only happens on the first request to the site. After that, the session is working fine and we only get one hit.
The Page_Load event of the content page will be called before the Page_Load of the master page as seen in steps 6-7 in the ASP.NET Page Lifecycle
The master page Page_Init event is called before the content page Page_Init event though, so if all you're doing is checking for Session, probably best to handle it in the Page_Init of the master page and redirect there. This could cause problems based on how other code in your project looks but conceptually, one of the first things you are wanting to do is check Session and handle properly so, you don't need page/controls to load before handling the redirect.
Try doing a Response.End() in the master page. This will halt the remaining markup from being rendered.

using master page

I have master page in asp.net.i want to display user in master page but in my knowledge master page is loading once at a time.How it possible when Session["User"] only get when login attempt.But master page is already loaded.
The master page renders with each page request, so if you have code that dynamically populates data on the page (for example, setting a label in Page_Load) it will populate on each subsequent page load. A master page can read from Session values just fine.
Have you tried something specific and it's not working?
try to put a breakpoint in pageload of aspx.cs and master page. Page will load first. and after that master page will load. So session added from page can be accessible form masterpage

how to update content page from master page?

Menu links are in the master page and and the corresponding click events are written in the master page itself. I have only one content page. Data is saved in html form in the DB and that will be rendered to the content page on corresponding menu link clicks. But the problem is content page load occurs before the master page so the content page is blank. Here my code-
public void GetLinkPage(Int32 linkId)//master page
{
LinkContentEnitity linkContent = new LinkContentEnitity();
linkContent = PageController.GetPageContent(linkId);
}
linkContent contains that content page in HTML form. How can I print this value on content page?
Though it's not entirely clear, it sounds like you are saying your content page needs information in its own Load event that is generated in the Page_Load event of the master page?
So either move the code that calls GetPageLink() to PreRender in your content page, or add an event handler in ContentPage for Page_LoadComplete() (which fires after all child controls on a page are loaded) and call GetPageLink() and do your rendering from there, e.g. in content page:
protected override void OnInit(EventArgs e)
{
Page.LoadComplete += new EventHandler(Page_LoadComplete);
}
protected void Page_LoadComplete(object sender, EventArgs e) {
// do stuff here, instead of OnLoad/Page_Load event
}
By the way this is a useful reference for event order. The problem you are having is very easy to get into when dealing with nested controls (master/content, usercontrols, etc), it helps to have a good understanding of the event order.
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
One way to do it might be this... On your content page, add a public method that does the work you need done. In the master page, cast this.Page to your page class and call that method.

Can I know what page is in my master page's ContentPlaceHolder?

All the Google finds I ran into tell me how to use FindControl to access a control on the master from the content page itself.
However, what I'm trying to do is the opposite.
From the master page, I want to reference whichever child page is in the ContentPlaceHolder.
Why you ask.
I want the master page to know which tab should be active depending on the content Page currently in the placeholder.
This lets me avoid having each page to reference the master page and allow them to change the active tab; that should be the master page's job (if there's a way it can know whom it's enclosing).
Thanks. No rants please.
If you are looking to get the instance of the executing page class, you can retrieve it from the current HTTP context:
var page = HttpContext.Current.CurrentHandler as Page;
From there, you can navigate the page's control tree, call FindControl(), and so on. Be cautious about page lifecycle, though, as master page events tend to fire before their page event counterparts.

Categories