Dealing with Databinding Errors in ASP.net - asp.net

This has been bugging me for a while but when I databind a control using with a Session variable as the parameter which has not been initialized there is an exception thrown which I can't seem to catch anywhere.
Ideally if the session varaible is not set I would just like to redirect but I can't seem to figure out where I need to check for this instance.

You must check the session object on page_init event.

Check it in your page load.
Sub Page_Load()
if Not Page.ispostback()
if session("Value") <>"" then
me.hiddenfield.value = Session("ValueName")
Else
Response.redirect("PAge.aspx")
End if
End if
End Sub
I tend to add some hidden fields as sessions eventually time out
then make the datasource use the hidden control for its reference

Related

ASP.NET, User Control and ViewState lost the correct data into try get into the user control event

Good afternoon, I have an ASP.NET web page and I created a user control that has some properties that I need to always be retrievable.
ViewState was added to keep information, but the drawback now is that when adding the same control on the same asp.net page and from within a function of the control I want to retrieve the value of the property, this will retrieve the last value entered in the ViewState .
Beforehand thank you very much.
<PersistenceMode(PersistenceMode.InnerProperty), TemplateInstance(TemplateInstance.Single)>
Public Property GuardadoTemporal() As Boolean
Get
If ViewState("GuardadoTemporal") Is Nothing Then
Return false
Else
Return CBool(ViewState("GuardadoTemporal"))
End If
End Get
Set(ByVal value As Boolean)
ViewState("GuardadoTemporal") = value
End Set
End Property
example for use
Use SaveControlState and LoadControlState https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.savecontrolstate?view=netframework-4.8
This will save it into the controlstate for each control so you don't get user controls clobbering each others data. controlstate can't be turned off either

Last Page Event Executed On Callback

I have a WebForm with many controls, including a large number of grids. I added some callback functions on these grids to refresh their DataSource and to update some global variables in a public static class after each refresh.
Normally I would add some method calls in the PageLoadComplete Event Handler, but the callbacks get raised after that. I also tried using the OnPrerender, OnPrerenderComplete and OnSaveStateComplete method overrides, but these don't seem to work with callbacks. (I can't use the OnUnload override since I need to use the Request object.)
And here is the Actual Question:
Is there any event handler I can use? Or can I create an event and raise it after everything else has finished?
I want it to execute as the last step in every callback/post-back of any kind (but before page unload so i can still use the Response and Request objects).
The grids are DevExpress's ASPxGridViews.
UPDATE
After searching for a while, I found out that the PreRender event is fired during async Postbacks of asp:UpdatePanels but not during DevExpress's Callbacks (it is normal behavior).
So, what would really help is finding/creating an event which I can use. I'm also thinking of grabbing the data I want from the Request Object during the PageLoad execution and using them later at Unload.
What are the pros and cons of each approach? Is there anything important that I need to know before making a decision, or is there anything I might be overlooking? I'm concerned about going with the second option since I'd have to declare some class variables and I feel like there are already too many of them.
Given the fact that the PreRender,PreRenderComplete and SaveStateComplete method overrides aren't executed during DevExpress's CallBacks, I found an alternative way to use the OnUnload Method.
First on the Page_Load Method, After some checks using the Request Object, and if the conditions are met, a Handler is attached to the Unload Event, and using a Lambda expression arguments are passed to this sub.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'//Some Code//
If Request.Params("__CALLBACKPARAM").Contains("REFRESH") Then
AddHandler Me.Unload, Sub() Page_Unload(sender,e,Request)
End If
End Sub
This way the Page_Unload sub will be executed only when needed, with all the arguments it needs, while successfully avoiding the addition of more global variables.
Protected Sub Page_Unload(sender As Object, e as System.EventArgs, req As HttpRequest)
'//Some Code//
End Sub
The only problem is that i cant remove this handler, but it is no big deal, since on every request to the server the objects are recreated.

.NET Master Page Session state variable not saving

I'm trying to store the session state in a master page to keep track of the previous URL. Here's what I'm doing
Public Property PreviousPage() As String
Get
Return Session("theprevpage")
End Get
Set(value As String)
Session("theprevpage") = value
End Set
End Property
Private Function HandleSiteNode(ByVal sender As Object, ByVal e As SiteMapResolveEventArgs) As SiteMapNode
Dim currNode As SiteMapNode = SiteMap.CurrentNode.Clone(True)
Dim tempNode As SiteMapNode = currNode
Dim strPrev As String = PreviousPage
' Append parent pages query string back onto the parent's node URL
If Not tempNode.ParentNode Is Nothing Then
If strPrev.Contains("?") Then
tempNode.ParentNode.Url = tempNode.ParentNode.Url + "?" + strPrev.Split("?")(1)
End If
End If
Return currNode
End Function
And in the master page load function
If Not IsPostBack Then
AddHandler SiteMap.SiteMapResolve, AddressOf HandleSiteNode
PreviousPage = Request.UrlReferrer.ToString()
End If
Now, here is where it gets strange.
The first page is a login page the master load doesn't get called on. After I log in it then going to the main.aspx page, and it successfully saves the "login.aspx" page in the session state.
Now, when I go to navigate the 2nd time after logging in, the session state is set successfully, but by the time it gets into the HandleSiteNode which is called after the session was set successfully, the session still says the url is "login.aspx" and not "main.aspx"
No where else in the code am I setting this session state, it just seems to revert back to its previous value on its own.
No matter how many links I click & how many times the session is set, the Session variable will never change to anything else besides "login.aspx"
Help!
edit: Another odd detail, when I move the AddHandler line from master page into a non-master page, the session state is saved properly. However, if I try to move the Addhandler code into the Master page MainContent.Load function, it still doesn't work
SiteMapResolve is a static event.
This means that it doesn't have access to the session object. You'll note this if you put a breakpoint in your HandleSiteNode code and inspect the Session.SessionId property.
The examples on MSDN about the event all target the global.asax file which means that handler is really geared towards a single use of the site. Note that the MSDN example I linked to is a little jacked in that it attaches a new event on every page load, which will eat memory. The event should only be attached to once.
Click here for more info on potential ways to get around the issues.
Apparently, my web project has at least 2 different session states.
I can access the session state that contains the value I want by using
e.Context.Session("theprevpage")
This seems like a bit of a hack but it's working for me.

Storing and restoring properties in ASP.NET derived control

I have created an ASP.NET class derived from the standard WebControls.TextBox, with the intention of adding extra properties that will persist between post-backs. However, I cannot figure how to get the values in these properties to persist.
I have tried setting the value of the properties into the controls ViewState as part of the PreRender handler, but the value is then not accessible in the Init handler on the post-back, because the ViewState has not yet been setup.
I could look for the ViewState value in the Load handler of the control, but if the page/usercontrol that is using the control asks for the properties value during its Load handler, the control hasn't yet reached it's Load handler, and it therefore not there.
My current class looks something like this...
Public Class MyTextBox
Inherits TextBox
Private _myParam As String = ""
Public Property MyParam As String
Get
Return _myParam
End Get
Set(value As String)
_myParam = value
End Set
End Property
Private Sub MyTextBox_Init(sender As Object, e As EventArgs) Handles Me.Init
If Page.IsPostBack Then
_myParam = ViewState("myParam")
End If
End Sub
Private Sub MyTextBox_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
ViewState("myParam") = _myParam
End Sub
End Class
I must be missing something really simple, such as whether there is an attribute I can set against the property.
UPDATE
Thanks to #AVD pointing out that I really had very little clue about the ViewState and the Init / Load stages, I finally figured it all out.
If you have the time (and if you're doing any major ASP.NET work, you need to make the time) please read the Understand ASP.NET View State document that #AVD pointed me to. It will explain a lot.
However, what it didn't explain is if you place your control within a <asp:Repeater>, you may as well throw all the rules out of the window... and that is exactly the problem I was experiencing.
In the end, the way I managed to get it to work was to use a <asp:PlaceHolder> control within the repeater, create an instance of my control within the ItemDataBound handler of the repeater, and then add the control to the <asp:PlaceHolder>... all done within the Init section (which fortunately I'm able to do).
As Andrew found out in this previous question you can end up in a chicken/egg situation, where you need to create the controls in the Init, but you won't know what controls you need until the Load.
(I have still made AVD's answer the correct one, because in the context of my original question, it is absolutely correct).
You have to store/retrieve value to/from ViewState within the properties accessors.
Public Property MyParam As String
Get
If IsNothing(ViewState("myParam")) Then
return string.Empty
End IF
Return ViewState("myParam").ToString()
End Get
Set(value As String)
ViewState("myParam") = value
End Set
End Property

Can't get Session variable the way I want to

Partial Class Preferences_MyPreferences
Inherits System.Web.UI.Page
Dim userID As String = Session("UserID")
This is just a page in asp.net. I want to be able to grab the Session("UserID") but every time I try, I get this error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
If I put that Dim userID inside say the Page_Load Event, then it works fine. Why does it have to be inside an event? I want to dim it once, and use it throughout the page.
Consider wrapping your call to the Session in a property in your code behind?
Public ReadOnly Property UserID() As String
Get
Return Session("UserID")
End Get
End Property
If you declare it as you have there, the variable is initialized and the session variable is expected to be ready for usage, but it is too early in the page life cycle to allow that. The preferred method would be as #p.campbell has suggested and wrap it in a Property or similar method. To answer the question though, the exception is generated because you are attempting to use session before it is available.
You need to read up on ASP.NET Page Lifecycles. The Session object doesn't become available until a certain point in the page lifecycle; if you want to grab the UserID once, you need to do it after the session becomes available.
The reason it doesn't work in your example is that the constructor for your Preferences_MyPreferences page is executed before the request object is available to the page. You should instead load it during the Page_Init or Page_Load event.

Resources