I have couple of user controls which are statically referenced in aspx. We are setting some public properties on the user controls in Page_Preinit event.
The page also references a master page
This was working fine so far. Had to do a ui redesign and we implemented nested master pages.
Now, all of a sudden, the user controls are showing up as null. If I change the master page to parent one (instead of child -nested), it works fine.
Appreciate any pointers to this issue.
some sample code: here ucAddress is null
protected void Page_PreInit(object sender, EventArgs e) { ucAddress.City = "Dallas"; }
This blog post describes the problem very well and also offers a solution. I can confirm that the solution works and I'll repeat the relevant parts here:
The problem
We have a user control and initialize its control in the Init event so that it is ready when the ViewState is restored (between Init and Load).
Once you start using this encapsulation technique, it won’t be long until you want to pass in a parameter that affects the data you load. Before we do, we need to be aware that the Init event is fired in reverse order. That is, the child controls have their Init event fired before that event is fired at the parent. As such, the Page.Init event is too late for us to set any properties on the controls.
The natural solution is to try and use the Page.PreInit event, however when you do you’ll often find that your control references are all null. This happens when your page is implemented using a master page, and it relates to how master pages are implemented. The <asp:ContentPlaceHolder /> controls in a master page use the ITemplate interface to build their contents. This content (child controls) is not usually prepared until the Init event is called, which means the control references are not available. For us, this represents a problem.
The Solution
The fix is remarkably simple; all we need to do is touch the Master property on our Page and it will cause the controls to become available. If we are using nested master pages, we need to touch each master page in the chain.
The author of the blog post then offers a nice little snippet that you can execute in the PreInit handler of your Page that uses a MasterPage and contains a user control:
protected override void OnPreInit(EventArgs e)
{
// Walk up the master page chain and tickle the getter on each one
MasterPage master = this.Master;
while( master != null ) master = master.Master;
// Access now initialized user control
ucAddress.City = "Dallas";
}
Found the issue. had to initialize child master page before accessing user control.
Related
I have some values that are set on a master page and that I want to save across a postback. I then want these variable to be available to pages using that master page during their load events.
Easy enough to create properties on the master page. So my first try to was to say that during the master page's load event, if not ispostback then generate the values and save them to the viewstate, else read them from the viewstate.
Except ... apparently the regular page load event happens BEFORE the master page load event, so the data wasn't there yet when I tried to read it.
Second try: have the master page set or retrieve these values during the Init event. No luck. Appears that the view state is not populated by Init time.
As far as I can tell, there's no event on a master page that happens after view state is populated but before the main page's Load event.
I suppose each page could have an InitComplete or PreLoad that calls a function to populate these fields, but that seems really clumsy. The call would have to be in every page. And it would have to be in every page even if that page never used this data, because the master page uses the data for its own purposes.
Is there a way to do this? Maybe view state is not the right place to save the data? I could store the data in Session variables, but then on not-postback the data in them would be left over from the last call. I guess I could make sure to clear the obsolete data, but that seems really clumsy.
I'm writing in VB but I wouldn't think that would make a difference here.
You could override LoadViewState method of the master page in the following manner:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
// use the loaded values, if any, here
}
LoadViewState is called before Load and in fact even before PreLoad of the page, so that seems to fit what you are looking for.
I am using this code to check if the request came from a page , if not then redirect somewhere.
string referer = Request.ServerVariables["HTTP_REFERER"];
if (string.IsNullOrEmpty(referer))
{
Response.Redirect("/UnauthorizedAccess.aspx");
}
It is working , I don't know whether it is perfect the solution.However I am checking this on load event of one of my page.How can I make it check on every request.Should I check this for all my pages.Also it is a good approach.Can anybody point me in the right direction.Any suggestion is welcome.
If you have logic that you would like to be run on the OnLoad of a bunch of your pages. You should probably create a BasePage that derives from Page and have the logic inside. Then all the pages you want that logic in can derive from BasePage instead of the regular Page.
Another approach can be using Master Pages
Note: After reading OPs additional comments. One thing to look out for when using a Master Page is that the Master Page's Page_Load event happens AFTER the Content Page's Page_Load event.
In other words the lifecycle is like this:
Master Page Init Event
Content Page Init Event
Content Page Load Event
Master Page Load Event
If your response.redirect moves the user to another page with the same master page (and same "validation" check) you might find yourself in an endless loop :)
If you have lot of pages, with these kind of common codes, than one possible solution is creating your own MyPage class as a child of the standard Page class. In your MyPage you can use something like:
Page_Load(object sender, EventArgs e)
{
string referer = Request.ServerVariables["HTTP_REFERER"];
if (string.IsNullOrEmpty(referer))
{
Response.Redirect("/UnauthorizedAccess.aspx");
}
base.Page_Load(sender, e);
}
Then any of your pages can inherit from this own MyPage class instead of the .NET's standard one.
In this way the common code reside in one place. In case of any change you have to modify that only there.
Or another possibility, you can consider using Master Pages.
I'm currently working on a dynamic core for several webprojects. It has a core that uses a treeview and a menu. And then for each specific projekt it loads several different wuc into a maincontent. Some business projects use business related wucs while others uses different ones. So the span of wuc's is really big.
Now to my problem, whenever a user press a menuitem or a treeitem it loads a wuc to the maincontent linked to that object.
But I'm having some viewstate errors and i've been looking around for 2 days now and none of the solutions explained are working for my projekt.
All my wuc has to have viewstate enabled.
Cycle is ->
Page(Control A) does postback with variable to change control to ControlB in wucPanel(UpdatePanel).
OnLoad LoadRequested Wuc.
Current code is
protected void Load_Page(object sender, EventArgs e)
{
//Code to decide which wuc to load.
UserControl wucc = (UserControl)Page.LoadControl(sFilePath);
ParentControl.ContentTemplateContainer.Controls.Add(wucc);
}
I've tried several fixes like adding diffrent ids to the wuc, but this either disabels the internal functions of control like handlers etc or generates the same viewstate error.
One solution i found was to load ControlA and then just removing it and then load ControlB. But this disabled the scripts for my 3rd party controller (Telerik).
I've also read about having diffrent PlaceHolders for each typof but since i expect havign up to 50 diffrent Controls I don't feel this is gonna help me.
And moving from Page_Load -> Page_Init generated the same error.
Error:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
In your case Anders, you still need to add the old control to your page in the init method along with the new control that you now want to add. Keep a reference to this old control that you have just added in a class level variable. So something like
Control _oldControl = null;
protected void Init_Page(object sender, EventArgs e)
{
//Code to decide which wuc to load.
UserControl wucc = (UserControl)Page.LoadControl(sFilePath);
ParentControl.ContentTemplateContainer.Controls.Add(wucc);
_oldControl = wucc as Control;
//Now add the new control here.
}
//override the LoadViewState method and remove the control from the control's collection once you page's viewstate has been loaded
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
ParentControl.ContentTemplateContainer.Controls.Remove(_oldControl);
}
Hope this helps. If it did, please check the checkbox next to this answer to accept it and vote it up if you like :)
In order to avoid ViewState related errors please make absolutely sure that in Page_Init you create the same control tree that was created the previous time ViewState was saved i.e. the previous postback. Simple page life cycle:
Page Init - create the control tree
- View State is loaded and applied here
Page Load - already loaded view state, you can do modifications to the control tree here
- Save View State
Page PreRender
For what it’s worth I recently had the same problem.
My scenario was as follows.
A fixed panel of filters (dropdown lists and textboxes) which built a search SQL string. On submission of the search consequent results were displayed in an editable gridview beneath.
On editing the gridview I cold effectively change the state of a database record thus removing it from the gridview under the filters previously chosen. In some cases this resulted in no results being returned thus causing me to hide the gridview.
I then found that if I used the new state of the record in the filter and resubmitted the search that error sometimes occurred.
The problem I eventually found had nothing to do with enabled viewstates etc but simply that the empty gridview, though no longer visible (changed programmatically), had not been rebound to a null datasource.
This appeared to cause the conflict and the error.
So it appears as though in my case the viewstate issue arose from a non-visible gridview that contained non-refreshed data.
I have a UserControl A that has to be loaded first and after that completes loading, I need to load a UserControl B.
I prefer to add both these user controls on the page at compile time (would like to avoid dynamic loading if possible).
If I add user controls on the page at compile time and set visible to false for User Control B, does it still execute the B's code behind? I can then set the visibility to true after loading User Control A
Should I be using events/delegates for notifying the completion of loading User Control A?
Don't load everything in the page event in control b, just put a method on control b to be called. Then add an event to control a which the page consumes, when the event is raised, call the load method on control b.
Edit: SampleCode
Ok so for example, create
a ASPX page
2x user controls
Put both user controls into the aspx page.
<cc:control1 runat="server" id="control_one" />
<cc:control2 runat="server" id="control_two" />
Then in control 1, create a delegate and event.
public delegate void MyCustomEvent (EventArgs args);
public event MyCustomEvent MyEvent;
protected void Page_Load(object sender, EventArgs e)
{
MyEvent(e);
}
So I have the event raised on page load. So you would have your logic in there thats required, when your done, calls MyEvent event.
In the page you want to add a handler for that event so when it's called you can do something with it.
protected override void OnInit(EventArgs e)
{
control_one.MyEvent += new WebUserControl1.MyCustomEvent(control_one_MyEvent);
base.OnInit(e);
}
void control_one_MyEvent(EventArgs args)
{
control_two.MyCustomLoad();
}
So when the page is initialized I add the event handler. In the event handler I call a custom method on the second control to load stuff.
Then in the second control I have:
public void MyCustomLoad()
{
//Stuff only loaded when event is raised and calls this method.
}
So this allows control 1 to load something, say it's done, when the page knows it's done, it can tell control 2 to do something.
Edit: After discussing this with a friend I'll explain what I mean by controlling the order.
You cannot control the order of page-life-cycle events. i.e: You can't have Control A, run through all it's page-life-cycle events, then once it's done, have Control B run through all it's page-life-cycle events.
If you do-away with the page life cycle, you can do a degree, as my example above shows, create a way of controlling the order in which the controls are rendered. By raising an event(s) at certain points when Control A is finished, you can tell Control B to do something.
The intermediate between the two controls is the page which handles the events raised by Control A which calls a method on Control B. You (well you can hack around to do it) can't specifically make Control A tell Control B to do something because that creates a direct dependency between the two controls which is bad.
Yes, the code behind will still run
Events could be useful
But if your controls have a specific dependency on each other, maybe they should just be a single control?
This is a fatally-flawed design. You should design your UI so that it doesn't matter in what order the controls load. The order in which controls load is outside of your control.
To address "Phill's" issue with an Order/Orderlines control pair:
I assume that the Order control was developed because it's useful by itself. I assume that OrderLines was developed to be able to show the line items for a given order displayed by the Order control.
I contend that there should be a single, composite control which combines Order and OrderLines. this control will pass to the OrderLines control, a DataSource consisting of the line items it is to display. This makes OrderLines independent of any other control - it simply displays the data it is told to display. It has no idea where that data came from.
Note that this can extend to a typical grid / detail / detail lines scenario, where you pass the grid a set of orders; when selected, a particular grid row will pass the Order control the selected order; when its' time to display the line items, pass the line items collection of the current order to the OrderLines control, etc.
This leaves each control with nothing to do but the Single job it is Responsible for.
"I have a UserControl A that has to be loaded first and after that completes loading, I need to load a UserControl B.
I prefer to add both these user controls on the page at compile time (would like to avoid dynamic loading if possible). "
I would suggest using WebFormsMVP: -
http://webformsmvp.com/
http://wiki.webformsmvp.com/index.php?title=Main_Page
As well as being a good implementation of Model-View-Presenter, one of the most useful features of this framework is its support for Messaging.
In a nutshell, you create Message Types, and your usercontrols (views) can post messages of whichever type you need to a message bus. Other controls can subscribe to messages of a particular type and the WebFormsMVP framework will ensure they are delivered.
This allows you to handle interaction between usercontrols by messaging publish & subscribe, without worrying about which order they load in.
Your only other option is to use dynamic control loading because, as others have pointed out, you can't rely on the order in which ASP.NET loads controls into a container.
I trying to implement a typical languages menu where users can select the language they want to view the site in through a menu that appears throughout all pages in the site.
The menu will appear on multiple master pages (currently one for pages where users are logged in and one for pages where users are not).
My current implementation is having a single master page base class (let's call it MasterBase). MasterBase has an event
public event LanguageChangedEventHandler LanguageChanged;
where LanguagedChangedEventHandler is simply defined as
public delegate void LanguageChangedEventHandler(string NewCulture);
MasterBase also has an overridable method
protected virtual void OnLanguageChanged(string NewCulture)
which just basically fires the event.
Each master page that inherits MasterBase overrides OnLanguageChanged and does the usual stuff like set the Thread's CurrentUICulture and the language cookie then does a
Server.Transfer(this.Page.AppRelativeVirtualPath, true);
to get the page to reload with localized values for the new culture. On the master page for logged in users it also updates the user's language pref in the db.
Each language option is currently a LinkButton on a master page that inherits from MasterBase. When the link is clicked it calls the base OnLanguagedChanged method passing in the correct culture info. E.g.
protected void btnEnglish_Click(object sender, EventArgs e) {
this.OnLanguageChanged("en-US");
}
Each page that needs to handle a language change then has some code in the page load that looks like...
((MasterBase)this.Master).LanguageChanged += this.Page_OnLanguageChanged;
// Where Page_OnLanguageChanged has the signature of LanguageChangedEventHandler
// and has stuff like reloading options in a drop down using the new language.
Quite a convoluted 'framework' =)
Firstly it's hard for new developers to know they have to hook up a method to the MasterBase's LanguageChanged event to handle language changes. Yes, we do document it. But still it's not something straightforward and obvious.
Secondly, all language changes are post backs. This is problematic especially when you want to navigate back with the browser Back button.
I'm looking for a more elegant solution. One that doesn't have both the problems above and also handles my current requirements.
Greatly appreciate any suggestions. Thanks.
It seems to me that it would be better to implement this in a control that sets an application variable that all pages could use. That way you could just implement the code in one place and have it always available on each page that displays the control (could be in your master's so all pages that inherit get it automatically). I think in the control you would have a handler that sets the global language setting and then reloads the page. Each page would check the language setting during page_load or prerender and load the proper localized strings accordingly.
I would just use the PreInit event on base page to set the current ui culture. I am not clear on why you would need each page to know when language is changed.