How can I change my page's Master Page at runtime? - c#

There is a requirement in one of my project, where I need to change Master Page during run time.
I mean I need to apply check and on the basis of that check particular master page can be called to my native aspx page.
Please help me out for same.
Thanks in advance :)

For example:
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
Apply your conditionals as required. From here.

Yes. Set the MasterPageFile property only during the PreInit page event—that is, before the runtime begins working on the request (since the rendering of the page with the master page occurs prior to the Init event)
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "simple2.master";
}
If you try to set the MasterPageFile property in Init or Load event handlers, an exception is raised.
Yes it is possible, Implement like below
Dynamically Loading Master Pages in ASP.NET 2.0

To acheive this we need to write code in Page_PreInit before page gets render.
Put below code into your code behind:
if (Session["userType"] == "Admin") //check the user type
this.Page.MasterPageFile = "~/Admin.master";
else
this.Page.MasterPageFile = "~/User.master";
Hope this helps.

Related

ASP.Net Web Form dynamic base page or hook page load event from out side

i have huge number of aspx pages. i want to fire a common function from all aspx page page load event but for that i need to add the function call in all page load event of all aspx page. so i am looking for a easy trick bu which i can make possible a function call from all page load event of all aspx page in my site.
so is it possible to hook page load event from out side or can we create a base page which will attached with all aspx page dynamically.
but i do not mean by base page like
public partial class MyBase: System.Web.UI.Page
{
}
public partial class index : MyBase
{
}
the above way i do not want to solve the problem bacuse if i follow the above way then i have to edit all aspx pages in my site. i need any easy trick to hook page load event.
please guide me.
EDIT
private void OnBeforeExecute(Object sender, EventArgs e)
{
var app = (HttpApplication) sender;
HttpContext context = app.Context;
//insert your code here
string sVal = BBAreman.CountryCookie.GetCookieValue();
if (sVal.Trim() == "")
{
Response.RedirectPermanent("~/country.aspx?ShowCountry=true", true);
}
}
i am checking cookie value...if found none then redirect to country.aspx. so when country.aspx load then again code try to redirect to country.aspx.....infinite loop start.
guide me how to code for this situation. thanks
Sounds like you need an HttpModule.
Your code then should look something like
public class MyModule : IHttpModule
{
public void Init(HttpApplication application)
{
//hook your onload event here. There are other events that could be more suitable
app.PreRequestHandlerExecute += OnBeforeExecute;
}
private void OnBeforeExecute(Object sender, EventArgs e)
{
var app = (HttpApplication) sender;
HttpContext context = app.Context;
//insert your code here
}
public void Dispose()
{
}
}
Do not forget to check out the module registration section in the link above.
Note: there are many more events that are fired in the asp.net pipeline, have a look here for a list of them. Maybe there is a more suitable event depending on what you need to do
EDIT
Since you posted the code, there are a few things you can do to improve this
DO NOT use RedirectPermanent in this case. A simple 302 Redirect is fine. Browsers tend to cache permanent redirects 'cause you know, they're permanent, no need to check again. So you end up with 2 infinite loops: a) the browser has cached the 301 and always redirects you to the country ballot screen, b) your code always redirects to the ballot screen anyway
You should insert some logic that checks whether the page is the ballot screen, and if so avoid redirection. Maybe something like this:
HttpContext context = app.Context;
if(context.Request.RawUrl.IndexOf("country.aspx",StringComparison.InvariantCultureIgnoreCase) > -1)
{
return;
}
//rest of your code here
An aside: you should have been able to figure this one out yourself. I took a look at your profile page, there are almost a thousand questions you asked, and the ones I sampled should be easy to research and resolve yourself. Something tells me you delegate all your programming to SO people. You get a -1 from me.

Page_Load method running twice

I have created a VS 2013 project using built-in asp.net Web Application Web Forms template. By putting a breakpoint in the Page_Load method of a page I can see the method is executed twice between pressing F5 and the page appearing. Why? And can I / should I stop this behaviour?
Apologies for not providing enough detail. The code is completely vanilla, untouched template code generated by VS Exp 2013 for Web.
The ASPX file is
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="mycompanyname.B1WebApp.About" %>
The ~/Site.Master has an empty Page_Load method (not sure this is relevant)
The code behind is
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Boolean Nothing;
}
}
You can avoid pageload function working on each postbacks by !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Your code here
}
}
A User control with this master page can also cause pageload execute twice...
This is part asp.net web forms, as a page posts back to itself whenever a server control is used on a page. It has been like this forever.
You need to do a check on page load:
if(!IsPostBack)
{
//Code for first time load
}
else
{
// code whenever you have a postback
}

Why is my session variable declared in master page blank on a web page?

I declared in master page load:
Session["sessionString"] = "stringX";
in my web page on load also, i call it
string sessionString= (string)Session["sessionString"];
i debug and value in web page is "" what is wrong?
The Page_Load event of a content page is called before the Page_Load event of the master page (see this SO answer and MSDN article). Hence, when you call
string sessionString= (string)Session["sessionString"];
in your web page, Session["sessionString"] does not contain any value yet and defaults to an empty string.
As a workaround, you could set the value of Session["sessionString"] on the Init or PreLoad events of your master page.
JW Lim is correct...content page's load event will fire before Master page load.
#user3445314 , you can use "Session_Start" event in Global.asax and set values same as you set in master page.
"Session_Start" event fires first and then your content page load event occur.
I hope this may be solve your problem
Declare Session in Master PreRender
protected override void OnPreRender(EventArgs e)
{
Session["sessionString"] = "stringX";
}
And get it by ContetPage OnUnload event
protected override void OnUnload(EventArgs e)
{
string sessionString= (string)Session["sessionString"];
}

How can I set MasterPageFile for MasterPage dynamically? [duplicate]

Okay, so we all know about changing a master page dynamically in a page's OnPreInit event.
But what about a nested master page? Can I change a master's master?
There is no OnPreInit event exposed in the MasterPage class.
Any ideas?
Just tested this and it works from the PreInit of the Page that is using the nested MasterPage.
protected void Page_PreInit(object sender, EventArgs e)
{
this.Master.MasterPageFile = "/Site2.Master";
}
Obviously you will need to ensure that the ContentPlaceholderIds are consistent across the pages you are swapping between.
We combine Andy's method with a "BasePage" class - we create a class that inherits from System.Web.UI.Page, and then all our pages inherit from this class.
Then, in our base page class, we can perform the relevant checks to see which root master page should be used - in our case we have a "Presentation" master, and an "Authoring" master - the presentation version has all the navigation and page furniture, along with heavy display CSS, while the authoring master has some extra JS for the authoring tools, lighter CSS, and no navigation (it's what we use when the user is actually authoring a page, rather than modifying the site layout).
This base page can then call Page.Master.MasterPageFile and set it to the Authoring master if that is the correct state for the page.
Just in case anyone stumbles across this and tears their hair out with a "Content controls have to be top-level controls in a content page or a nested master page that references a master page" error when trying Andy's code, get rid of the this.Master. So, the code becomes:
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "/Site2.Master";
}
Edit As Zhaph points out below, the code I have ^^ there will only change the current page's master, not the master's master. This is the code Hainesy was talking about when he mentioned "we all know about changing a master page dynamically" (which I didn't, d'oh). If you happen to get to this page by googling "stackoverflow change master page" (which is what I did) then this is possibly the code you're looking for :-)
To add on to the answer of Zhaph - Ben Duguid, (+1 by the way):
Here is example code that sets the master page of the nested master page. All pages inherit from this BasePage, so this code only exists in one place.
public class BasePage : System.Web.UI.Page
{
private void Page_PreInit(object sender, System.EventArgs e)
{
if (Request.Browser.IsMobileDevice)
{
if (Page.MasterPageFile == "~/master/nested.master"))
{
Page.Master.MasterPageFile = "~/master/mobile.master";
}
else
{
MasterPageFile = "~/master/mobile.master";
}
}
}
}

page_load event in Master and Content Pages

Here is the sequence in which events occur when a master page is merged with a content page:
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
So, my problem is:
I have one login page (not use master page), one master page, and hundreds of content page.
I check login session Session["loggedInUser"] in master page (if not logged in, redirect to login page)
So, when I don't log in, if I type the address of one content page, it must check login session in master page and redirect to login page, right? But it has two cases here:
If in content page, I don't use anything related to Session["loggedInUser"], it will redirect to login page, so, it's OK here!
The second case: if I use Session["loggedInUser"] to display Username in content page for example:
UserInfo loggedInUser = (UserInfo)Session["loggedInUser"];
it will return null object here, because the page_load in content page is fired before page_load in master page, so it thows null object instead of redirecting to login page.
I also tried Page_PreInit in master page but no help
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
}
Any suggestion?
Presumably, when you say you are using the Session["loggedInUser"] value, you are then calling .ToString() method or similar to display it?
In which case, you will need to check for a null object before using it. It would be best practice to check for the existance of the object before using any methods on it in any case, so:
if (Session["loggedInUser"] != null)
{ ... }
Only if you are certain that the code will never be executed without the Session object being instantiated can you use methods without checking for a null reference.
http://msdn.microsoft.com/en-us/library/03sekbw5.aspx
Finally I've come up with a solution:
I create a class BasePage like this:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
base.OnLoad(e);
}
}
And in the content page, instead of inheriting from Page, I change to BasePage and it works perfectly
Thanks for all of your support
Nice day ;)
You could check for Session["loggedInUser"] in the content Page's Page_PreRender() rather than Page_Load()or alternatively, do the master page check in the Page_Init() rather than Page_Load(). We had the same problem and went with the Master page Page_Init() option, so that we could still use Page_Load() in all the Content pages.
Edit: It's Page_Init() not PreInit().
I have 2 masterpages(1 for prelogin,2nd for afterlogin),home page is independent,logout page inherits postlogin page) in all postloginpage session chck if sessionnull(xyz)else(redirect loginpage) all this in Page_Init event of afterlogin.master................Successfull

Categories

Resources