Reputation: 9043
I started to experiment with ViewState. The reason I want to use it is to add the value of a user name to the web page(Web Forms Project) when he or she logs in successfully.
I assign a name after log in and the redirect user to Default.aspx upon successfull login.
ViewState.Add("UserFirstName", name);
Response.Redirect("Default.aspx");
When Default page loads I try to retrieve retrieve the value and assign it to a label in the Site.Master.
The value however is null.
userName = ViewState["UserFirstName"].ToString();
SiteMaster master = (SiteMaster)Page.Master;
master.labelInfo = "<strong>Welcome</strong> " + userName;
Sorry if I come accross as extremely ignorant and inexperienced but what is the best solution to maintaining this user name value without making use of QueryStrings or Session variables?
Upvotes: 0
Views: 91
Reputation: 14350
As others mentioned ViewState is maintained through encoded data that is embedded in a HiddenField. Once you leave the page that HiddenField is obviously no longer available.
I share your distaste for Session variables, though Session is the best way to do this. There is a concept from MVC that you can use, though you would have to implement it, called TempData. The idea is basically to wrap a Dictionary which is held in Session, such that either every read would mark that entry to be cleared out, or every page load would kill the whole TempData dictionary.
Since Session is essentially a global variable with contents that never run out of scope, A TempData-like solution is (I think) better for transferring information from one page to the next as it essentially runs out of scope once you are done with it.
Upvotes: 1
Reputation: 5679
Since you explicitly don't want to use Session variables (which is really the best way to do this), about the only other option you have is to set a cookie when the user logs in to store the user's name, and read that cookie on each subsequent page - of course this is not much different to using session state (and much less secure, for what that's worth).
Upvotes: 1
Reputation: 63956
The ViewState is only maintained if you stay within the same page. That's why when you redirect to another page the value is NULL. The ViewState is kept in a base-64 encoded hidden field within the page. For what you are trying to do, Session
would be a better choice:
Session["Username"]=name;
Response.Redirect("Default.aspx");
And then on Default.aspx
string name = Session["Username"];
Upvotes: 3