What is the most correct asp.net page lifecycle event to change a label's text? - asp.net

Joined a company that use Asp.Net, a tech that I had never worked with before. I have a very simple task to do which is to change a label's text depending on a value that is included in the logged in user's session.
I considered Init, Page Load and PreRender and ended up placing my code in the PreRender event and got a comment in a code review from the main code reviewer saying "this does not belong here, go and investigate the page lifecycle to figure out why"
According to the docs:
Init should be used to "initialize control properties" (which seems to be about right for this case).
Page Load should be used to "set properties in controls and to establish DB connections".
PreRender should be used to "make the final changes to the page or its controls"
I can't see an obvious event that should be used instead of the others. I wrote above that Asp.Net is new to me so I may be missing something.
Which event should be used in this particular case, and in general, to change properties of controls?

Related

Asp.net output cache substitution with postback in user control

We have a site where all pages are output cached, i.e. the caching is on aspx-level with VaryByParam="*". Now there is a requirement to make a gallup control, i.e. a small "How is this site working for you?" and then when the user clicks an answer the results are shown.
The gallup is implemented as a usercontrol that is added to the master page so gallups can be added to any page to which a gallup is created in the cms. The problem is that output cache naturally caches all clicks so when user no 2 votes he sees the results that where calculated after the first vote on that alternative.
Now I'm trying to use cache substition. I added an asp:Substition tag where the user control used to be, load the control dynamically and render it (using this approach http://coderwall.com/p/4ajzqq). The problem is that the postbacks that voting triggers is never fired. Apparently the method that the substition control executes is loaded outside the page life cycle or too late.
Any ideas?
Regards,
Mathias
I solved this by skipping the substitution control and just used the user control as normal, so the gallup/question view was output cached. Then in the click handler for the answer alternatives I added
Response.Cache.SetNoServerCaching();
which exempted the results view from output cache and hence it was updated as it should.
It is also possible to use Response.Cache.SetNoServerCaching() in Global.asax, using VaryByCustom. It merely requires sensing in Global.asax whether the page is a post-back or not. Here is a code example.

What are the main differences of defining a control statically or creating it dynamically on page load?

I am working on a project which creates controls dynamically for a form in the page_load event, loads in their current values from the database and saves their values (using FindControl) when the user clicks the continue button.
When I added a control statically in the .aspx page and followed their same procedure of loading the value in the page load and saving it on the button press I found that the value would not save correctly. It seems that it wouldn't save because the click event fires after the page_load, so the page_load of the post back reverted the value and the user entered value was not saved.
The strange thing is that by changing the control to be dynamically created just as all the other controls on the page and keeping the loading and saving the same it now works. Even though the page load still creates the control with the old database value.
It seems like a very fundamental asp .net feature here but i'm just unclear as to what is going on. I suspect it is to do with the timing of creation and maybe when the view state kicks in.
Static page controls are created just like dynamic page controls. The difference might be coming in your Page_Load. Whenever you postback all the controls are created afresh which means they are created with their initial values. This happens because after creating the controls asp.net throws away the controls/objects.
So, when the request comes, the first thing that asp.net does it to recreate the controls by looking at their definitions (in the designer files). On each postback they are created and initialized again losing their state in the process.
But after creating the controls Asp.Net loads any viewstate that is sent along with the request which makes people think that the state is always saved at the server.
What might be happening is that either the viewstate is not enabled for your control (in case they are created in designer), in which case you may try using EnableViewState property to true of the control.
Or, when you're doing a Page_Load, you're forcefully re-initializing everything. And in process losing all the control data. If you could post the logic of Page_Load, it might get clarified.
Make sure that:
you are not setting the value again for the static control in Page_Load. The dynamic control are probably getting around it by grabbing the ViewState and form values at a different stage in the lifecycle.
The dynamic controls are added After the static control. Or at least they are added in a different container. Placement in the control's collection can affect the ViewState, although it doesn't look like your scenario / since what you mention seems to be more about the values in the current post.
The save is happening After the Page_Load in response to the corresponding event.
I've run into similar problems in the past (quite a few times actually), but what helped me the most is understanding the ASP.NET Page Lifecycle.
Microsoft has an article on it which describes it pretty well, but this post by Solomon Shaffer really cleared up everything.
I suggest reading them both and coming back with additional questions regarding to a particular state, when to load/save data etc..
Hope this helps.
Marko
Note that you may want to use Page.IsPostBack property to avoid reinitializing values on button clicks and other events.
private void Page_Load()
{
if (!this.IsPostBack)
{
// Assign values to the controls.
}
}

ASP.NET: How to initialize when *user control* is initially loaded

I have an ASP.NET user control that I'm embedding in another user control. This works fine.
I need to know the best logic/method for detecting when the control is loaded. In other words, I have some display initialization logic that needs to run when the control is initially displayed. Surely there is a pattern for this.
The typical method is to put (!IsPostBack) logic in the Page_Load method of the control. This works great until you end up with a state when the Parent page has already posted back many times. My user control gets added to the page but its display does not intialize properly.
I'm hoping to find a way that keeps this logic inside the control, versus various hacking around in the codebehind of the parent page.
See the following MS article. They have an example that places several controls within a user control and initializes them.
There is another post here on StackOverflow that seems similar. You may want to check it out, and see if it points you in the right direction.
It may also be helpful to review the page life-cycle and events.

Why does my session variable appear to empty itself in ASP.NET?

I have user control on a ASP.NET web page, which contains a GridView and a radio button selector.
In the underlying middle tier I have a thread which goes to the database and then raises an event to say "I have some data" my User control handles this event and sets a Session Variable.
This works and I can see the event being handled and the Session variable gets the new data.
However when i go to use this session variable when the selected index of the Radio button selector changes the Session variable reports as "Nothing"
I have ensured that the obvious (i.e. spelling, Sessions switched on etc) are correct.
The GridView and radio button selector are encapsulated in the same Update panel.
Check that if your UpdatePanel - updatemode is set to 'Conditional'? also Child as triggers? I would first start by putting a stop in your page load, see whats happening from there. Do a search for all places where you populate that session variable and put a stop. You may be surprised, I have often found that page lifecycle gets confusing even though I thought I understood it. Alt - post some code and we can step through.
Yeah, sounds almost like a problem with order of operations or not checking for postback on a page load or something?
Like JamesM suggested, running your website in debug mode should really help identify the problem. You can bring up your watch window and set it for the Session variable you're looking for, then set breakpoints all over and check the value at each stop to divide and conquer the code.

How do I persist the value of a label through a response.redirect?

Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):
aspx:
<asp:Label runat="server" Text="default text" />
Code-behind (code called on an onclick event):
Label.Text = "foo";
Response.Redirect("Default.aspx");
When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.
For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.
A Response.Redirect call will ask the user's browser to load the page specified in the URL you give it. Because this is a new request for your page the page utilises the text which is contained in your markup (as I assume that the label text is being set inside a button handler or similar).
If you remove the Response.Redirect call your page should work as advertised.
After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept.
Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, until you change the page without a POST. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url.
ASP and ASP.Net are inherently stateless unless state is explicitly specified. Normally between PostBacks information like the value of a label is contained in the viewstate, but if you change pages that viewstate is lost because it is was being stored in a hidden field on the page.
If you want to maintain the value of the label between calls you need to use one of the state mechanisms (e.g. Session, Preferences) or communication systems (Request (GET, POST)).
Additionally you may be looking for Server.Transfer which will change who is processing the page behind the scenes. Response.Redirect is designed to ditch your current context in most cases.
To persist state, use Server.Transfer instead of Response.Redirect.
So, if I may answer my own question (according to the FAQ, that's encouraged), the short answer is, you don't persist view state through redirects. View state is for postbacks, not redirects.
Bonus: Everything you ever wanted to know about View State in ASP.NET, with pictures!
For what it's worth (and hopefully it's worth something), Chapter 6 of Pro ASP.NET 3.5 in C# 2008, Second Edition is a terrific resource on the subject. The whole book has been great so far.

Resources