473,804 Members | 3,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP.Net ViewState and InitializeCultu re

Telinstryata
11 New Member
Is there a way to read the ViewState by using Request.Form("_ _VIEWSTATE")? I want to read a value from the ViewState during the InitializeCultu re function, but the ViewState object isn't initialized until after the Init portion of the ASP.Net Page Life Cycle. The following code always crashes once the Session times out, because the ViewState is always Nothing until after the Init portion.

Expand|Select|Wrap|Line Numbers
  1.     Public Property CurrentUICulture() As String
  2.         Get
  3.             Return ViewState(CURRENT_UI_CULTURE)
  4.         End Get
  5.         Set(ByVal value As String)
  6.             ViewState(CURRENT_UI_CULTURE) = value
  7.         End Set
  8.     End Property
  9.  
  10. Protected Overrides Sub InitializeCulture()
  11.         If Session(CURRENT_UI_CULTURE) Is Nothing Then
  12.             ' If not read from the VS
  13.             Thread.CurrentThread.CurrentUICulture = New CultureInfo(CurrentUICulture)
  14.             Session(CURRENT_UI_CULTURE) = CurrentUICulture
  15.         Else
  16.             ' If so, read from the Session
  17.             Thread.CurrentThread.CurrentUICulture = New CultureInfo(Session(CURRENT_UI_CULTURE).ToString)
  18.             CurrentUICulture = Session(CURRENT_UI_CULTURE)
  19.         End If
  20.         Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture
  21. End Sub
  22.  
Nov 19 '08 #1
7 6798
Frinavale
9,735 Recognized Expert Moderator Expert
What are you doing here:
Expand|Select|Wrap|Line Numbers
  1.  Public Property CurrentUICulture() As String
  2.          Get
  3.             Return ViewState(CURRENT_UI_CULTURE)
  4.          End Get
  5.          Set(ByVal value As String)
  6.              ViewState(CURRENT_UI_CULTURE) = value
  7.          End Set
  8.      End Property
  9.  
You can retrieve the Current UI Culture from the current thread.


Please see my comments in the following code:
Expand|Select|Wrap|Line Numbers
  1. Protected Overrides Sub InitializeCulture()
  2.          If Session(CURRENT_UI_CULTURE) Is Nothing Then
  3.              ' If not read from the VS
  4.  
  5. 'Don't do this...........Why are you doing this????
  6.              Thread.CurrentThread.CurrentUICulture = New CultureInfo(CurrentUICulture)
  7.  
  8.              Session(CURRENT_UI_CULTURE) = CurrentUICulture
  9.          Else
  10.              ' If so, read from the Session
  11.              Thread.CurrentThread.CurrentUICulture = New CultureInfo(Session(CURRENT_UI_CULTURE).ToString)
  12.              CurrentUICulture = Session(CURRENT_UI_CULTURE)
  13.          End If
  14.  
  15. 'What is the point of this??????
  16.          Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture
  17.  End Sub
  18.  
-Frinny
Nov 19 '08 #2
Telinstryata
11 New Member
Basically, I need to create a website that is available in both English and French.

1. The user is started with a page that lets them choose their preferred language.
2. Once in the application they can switch their language and all it does is switch the language of their current page.

Currently, I store the selected language is a Session variable and then set the culture of the page to their selected language, so that the correct Resource files for the language are used. If they switch languages then I change the Session variable to the opposite language and to a redirect back to the current page. As long as the Session doesn't expire this works fine, but this fails when the Session times out. I need some way to save their selected language, without using Cookies, so that if the Session times out, I can still find out what language they had selected and not force them to choose their language again. I was hoping to use the ViewState to store the selected language, but ViewState is unavailable in InitializeCultu re, because it hasn't been initialized by that point in the process.
Nov 19 '08 #3
Frinavale
9,735 Recognized Expert Moderator Expert
I hate to tell you this but in order to use Session you are already setting a Cookie....

Also, storing the user's preference in ViewState will not work no matter how much you wish it would....as you already know, ViewState is loaded after the InitializeCultu re event and so this technique will always fail.. That's just how things work. So you need to find another way to store your user's preference....t hat's why cookies are commonly used for this purpose.

Anyways, I've managed to implement a quick solution to your problem that doesn't use cookies and reduces a whole Response.Redire ct....which I kind of like.

The solution involves using JavaScript to set an hidden field to the language that the user has selected. You can then retrieve this value through Request.Params( ) to determine the language to set the page to.


Place a hidden field in your ASPX page:
Expand|Select|Wrap|Line Numbers
  1. <asp:HiddenField ID="languagePreference" runat="server" />
Also place the following JavaScript code in your ASPX page:
Expand|Select|Wrap|Line Numbers
  1.  <script type="text/javascript">
  2.        function loadLanguage(langCode)
  3.        {
  4.          /*setting the hidden field's value to be the language code the user picked*/
  5.          document.getElementById('<%= languagePreference.ClientID %>').value=langCode;
  6.          return true;
  7.        }
  8.  
  9.       function setName()
  10.       {  
  11.          /*setting the Name of the hidden field so that we can retrieve it on the server using Request.Params()*/
  12.         document.getElementById('<%= languagePreference.ClientID %>').name='languagePreference';
  13.        }
  14.     </script>
  15.  
You need to call the setName JavaScript function in your <body> tag's onload event. This function sets the hidden field's "name" so that you can retrieve it's value using the Request.Param() on the server. If you don't set this, the name will be set to the same thing as the hidden field's ClientID....whi ch is unobtainable in the InitializeCultu re event.

Expand|Select|Wrap|Line Numbers
  1. <body onload="setName()">
Set the OnClientClick in your buttons to call the JavaScript, passing it the language code you want display the page in. I used LinkButtons when implementing this solution...but it's the same idea if you are using regular buttons.

Expand|Select|Wrap|Line Numbers
  1.  <asp:LinkButton ID="French" Text="French" runat="server" 
  2.         meta:resourcekey="FrenchResource1" OnClientClick="return loadLanguage('fr');"></asp:LinkButton>
  3.     <asp:LinkButton ID="English" Text="English" runat="server" 
  4.         meta:resourcekey="EnglishResource1" OnClientClick="return loadLanguage('en');"></asp:LinkButton>
  5.  
Now in your InitializeCultu re method all you have to do is the following:
Expand|Select|Wrap|Line Numbers
  1.     Protected Overrides Sub InitializeCulture()
  2.         Dim languagePref As String = Request.Params("languagePreference")
  3.         If String.IsNullOrEmpty(languagePref) = False Then
  4.             Thread.CurrentThread.CurrentUICulture = New CultureInfo(languagePref)
  5.         End If
  6.     End Sub
  7.  
You don't even have to put any server side implementation for your button click events! There's no need to do a Response.Redire ct because everything's already set :)

It just loads the page using the language you specified right in the InitializeCultu re method :)

Please note that it will use the default resource if no language is specified.

One last thing, you have to set the hidden field's value to the language code in the PreRender or else the value will be lost.
Expand|Select|Wrap|Line Numbers
  1.   Private Sub _Default_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
  2.  
  3.         languagePreference.Value = Thread.CurrentThread.CurrentUICulture.ToString
  4.   End Sub
  5.  
Cheers!

-Frinny
Nov 19 '08 #4
Telinstryata
11 New Member
Thank you very much for the work you put into this.

I was sort of hoping that I would be able to come up with a solution that I can place in a base class and everything would be handled automatically. So, no JS function calls needed on every link/button, no hidden fields on every page. It's really a catch 22. If I put my code in the PreLoad the ViewState can be read, but by that point it's too late to set the culture. If I put it in the InitializeCultu re it's too early because there's no ViewState yet. I need something in between where I can set (or reset) the culture after the ViewState becomes available.

I guess I should have stated that I was hoping to avoid manual cookies, I'm fully aware that sessions use cookies, but, you know, out-of-sight out-of-mind.

I'm not going to give up on this, and if I find anything I'll be sure to post it back here.
Nov 19 '08 #5
Frinavale
9,735 Recognized Expert Moderator Expert
Thank you very much for the work you put into this.

I was sort of hoping that I would be able to come up with a solution that I can place in a base class and everything would be handled automatically.
If youo have to override the InitializeCultu re event in every ASPX page, implementing a base class for all the Pages in your project that has the InitializeCultu re event defined it may be really helpful.
So, no JS function calls needed on every link/button, no hidden fields on every page.
You don't need to apply the JS calls to every link button on the page.......just the link buttons that change the language....and you only have 2: English and French.

And you can place the hidden field in the MasterPage if you want.
Just be aware that you wont be able to access it in the VB code for your master page to set it's value in the PreRender event...so you'll have to come up with another way to set it...ie add it to the setName JavaScript function.

2. Once in the application they can switch their language and all it does is switch the language of their current page.
According to this requirement you don't even need to remember the language preferences between pages in your site.......so you don't even need to store it in Session.......n or do you even need to put the hidden field in the master class...because every page's settings are unique.

It's really a catch 22. If I put my code in the PreLoad the ViewState can be read, but by that point it's too late to set the culture.
So this obviously wont work.

If I put it in the InitializeCultu re it's too early because there's no ViewState yet.
So, don't use ViewState....

I need something in between where I can set (or reset) the culture after the ViewState becomes available.
This doesn't exist.

I guess I should have stated that I was hoping to avoid manual cookies, I'm fully aware that sessions use cookies, but, you know, out-of-sight out-of-mind.
Cookies really are your friend here if you're not willing to use a hidden field.
Nov 19 '08 #6
Nice trick Frinny !
Changing language without redirect and loose viewstate... is great.
thanks
Sep 29 '10 #7
Frinavale
9,735 Recognized Expert Moderator Expert
I'm glad it was helpful for you :)
Sep 30 '10 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

9
21653
by: John Kirksey | last post by:
I have a page that uses an in-place editable DataGrid that supports sorting and paging. EnableViewState is turned ON. At the top of the page are several search fields that allow the user to filter the results in the grid. Say you filter the grid for records that have a certain condition set to "NO" (in this case a checkbox). In this scenario the search returns one result. If I then check the checkbox ("YES") and save it, I now get my message...
0
8539
by: blackstaronline.net | last post by:
Hi, I'm using .NET V2.0 I have been using un-compiled code behind pages for my .net app using "Src" in the @Page. I randomly get an Initialized Culture error when trying to access the page. Many times I can simply refresh and the app runs fine. I have not messed with the culture setting at all. At first I thought it was the server so I switched web servers but got the same random error. It only happens maybe 10% of the time. After...
0
1412
by: Maury | last post by:
Hello, I ovverride the method InitializeCulture of a page to change programmatically a language in a site, I would like to do this after the user clicks on a button, but the button_click event raises after the InitializeCulture event so I have to click twice to view the new language... how can I fix this? Thanks! M.
1
6547
by: Mohammed Banat | last post by:
All my pages work just fine on development, but as soon as I publish (deploy), I always get Compiler Error Message: BC30456: 'InitializeCulture' is not a member of 'ASP.default_aspx'. This happens for every page. Please help. I have seen multiple questions from people on this same issue, but with no answers.
0
1417
by: Jon Paal | last post by:
After adding some code to codehehind for my vb aspx page, I am now getting this error: "InitializeCulture is not a member of ASP._aspx" if I move the codebehind back to inline script , then the page works. What's with this error message ?
3
7217
by: Mauricio Pires | last post by:
All my pages work just fine on development, but as soon as I publish (deploy) to a W2K Server with .Net Framework 2.0 , I always get Compiler Error Message: BC30456: 'InitializeCulture' is not a member of 'ASP.default_aspx'. This happens for every page and after I created a MasterPage. Please help. I have seen multiple questions from people on this same issue, but with no answers.
5
7352
by: =?Utf-8?B?SGVyYg==?= | last post by:
My long-running ASP application just stopped working today. I rebuilt and republished, but to no avail. The full error is: Server Error in '/NuclearDedication' Application. -------------------------------------------------------------------------------- Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details
4
14185
JustRun
by: JustRun | last post by:
Hi, I'm trying to develop a MultiLanguage web site using ASP.NET 2.0 with C# My problem is: I want to make my MasterPage support switching among languages, but when i put the "InitializeCulture()" inside the masterpage.cs, I got this erreor: MasterPage.InitializeCulture()': no suitable method found to override Note the following code works fine with xxx.aspx page, but not with MasterPage Here is my code: public override void...
1
2001
by: RN1 | last post by:
I have an ASPX page with all the subs & functions. I created a code- behind for this ASPX page & moved the entire code except for the GUI code in the code-behind. I also added the CodeFile & Inherits attributes to the Page directive. Now when I run the ASPX page, the following error gets generated: ------------------------ 'InitializeCulture' is not a member of 'ASP.ets_aspx'. ------------------------
0
9588
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10589
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.