Reputation: 5348
I have an MVC application which sets some session variables based on internal static IP addresses.
I have built an ApplicationController to override the OnActionExecuted sub in MVC for data that I need to use throughout my application.
However, the code below, which is just a snippet of my code but is edited for my post, only partially works. On initial page load, the session variables aren't saved, but after a page refresh they are. The issue I have is that these need to be saved on the initial page load.
If Session("Item1") = Nothing Then
If IpAddressShort <> "" Then
Dim locInfo = cmsRepository.GetInfoBasedOnLocation(IpAddressShort).SingleOrDefault()
If locInfo IsNot Nothing Then
Session("Item1") = locInfo.Item1
Session("Item2") = locInfo.Item2
Session("Item3") = locInfo.Item3
Session("Item4") = locInfo.Item4
If locInfo.Item2= "1" Then
Session("Visibility") = 3
Session("TypeShort") = "XXXX"
ElseIf locInfo.Item2= "2" Then
Session("Visibility") = 4
Session("TypeShort") = "YYYY"
ElseIf locInfo.Item2= "9" Then
Session("Visibility") = 2
Session("TypeShort") = "ZZZZZ"
End If
End If
End If
End If
Theoretically, if I'm correct, if there is no Session("Item1")
set/if Session("Item1")
is empty, then the rest of the snippet should run and set those variables.
How come this isn't setting those variables on the first time the page load?
Thanks for any help in advance
Upvotes: 0
Views: 1799
Reputation: 47766
The documentation for OnActionExecuted states:
Called after the action method is invoked.
In your initial call the data is not there because the action hasn't finished executing. T he OnActionExecuted
hasn't run yet because it will run after your action has completed. The second time it is there because OnActionExecuted
has run from the last action.
What you want is the OnActionExecuted which states:
Called before the action method is invoked.
This will happen before your action code so the first time it action executes this will have all happened first and then your action code will fire.
This is a great article explaining the ASP.NET MVC life cycle:
http://blog.stevensanderson.com/2007/11/20/aspnet-mvc-pipeline-lifecycle/
Upvotes: 0
Reputation: 7280
I assume that you are determining that the session data is not present because you cannot access it from within your action method.
If this is the case then try overriding OnActionExecuting
instead as this is called before the action method. OnActionExecuted
is called after the action method.
Upvotes: 1