ASP.NET const string session key lost on PostBack - c#

My session key is a const string variable. See below.
On first Page Load, I add a string to the session using this key. I also indicate to KeepAlive on the key on the first load and every PostBack. However, on PostBack, I notice that the key is no longer in the session.
I found that to fix this, I simply have to remove "const" from the variable, and everything works fine.
Can someone explain and provide any educational resources on why this is happening.
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
public string CurrentEntity
{
get { WebClientSession.Current[ENTITY_KEY] as string); }
set { WebClientSession.Current.AddTransient(ENTITY_KEY, value); }
}
protected void Page_Load(object sender, System.EventArgs e)
{
string key = (string)Request["Id"] + "";
CurrentEntity = Mapper.Lookup.FindById(key);
WebClientSession.Current.KeepAlive(ENTITY_KEY);
}
private void _bindGrid()
{
...
// CurrentEntity is null here on PostBack. Good on first load.
...
}

I am not sure what WebClientSession is but the HttpSessionState will work with const. There is no reason why it should not work. Here is the proof that it will work:
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
protected void Page_Load(object sender, EventArgs e) {
if( !this.IsPostBack ) {
Session.Add( "ENTITY_KEY", ENTITY_KEY );
}
}
protected void Button1_Click(object sender, EventArgs e) {
string s = Session[ "ENTITY_KEY" ].ToString();
}
I simply added a button to my form. In the load method if the page is being requested I added a const variable's contents to the Session. In the click handler of the button, which is the form being posted, I access it from the Session and it is there.
So why is it not working for you?
There are 2 possible reasons:
Reason 1
The issue is in your WebClientSession class. I do not know the details of that class so cannot say what the issue is.
Reason 2
Session is stored in memory on the server. So, if this site is deployed on a farm, it is possible that the server which served the page initially added the ENTITY_KEY to Session. But when the page is posted back on the button click, another server serves the request. This server may not have the ENTITY_KEY in its memory since it is possible it has never served that page yet. In a web farm, you would want to use another source to store session related data such as a database or a file etc.

Related

How to use ViewState after Request.Form?

Hi I'm trying to save the values from the request.form after post back. I've tried to use viewstate on the input string but the page_load keeps regenerating the request.form
string TID = null;
Protected void Page_Load(object sender, EventArgs e)
{
if (TID == null)
{
TID= Request.Form ["totalID"];
}
Label1.Text = TID;
}
protected void Button2_Click (object sender, EventArgs e)
{
Label1.Text = TID;
}
Most asp.net controls have a text property, so if yours is a TextBox and you named it textBoxTotalID, then you can just get the value entered using this.textBoxTotalID.Text.
Instead of totalID, use the name of the element not the Id. The name is used for posting information to the server. And also make sure you have specified a name in your view for the element whose value you need on post.
In addition to that, ask yourself this question: Do you need to do that even when the user requests the page or only when the form is submitted? I am sure your answer is only when form is submitted. In that case, do it only when IsPostBack is true.
Try adding a check to the IsPostBack property.
if (IsPostBack)
{
//Set Values here
}
This is set to true when the page is responding to a post back from a form submit or perhaps a control event being fired.

ViewState doesn't remember value from previous page init

What am I doing wrong here. I can't get ViewState to work:
protected void Page_Init(object sender, EventArgs e)
{
Method1();
}
private void Method1()
{
Element.Click += new EventHandler(Button_Click);
}
public void Button_Click(object sender, EventArgs e)
{
if(ViewState["x"] != null)
// use ViewState["x"] from previous Page Init
//do processing ...
//in the end, store value for future use
ViewState["x"] = myLabel.Text;
}
I am reloading the page, so first the Page Init is triggered, where I do changes, before these changes I read from ViewState previous value of a variable, then I do processing, then override that value for subsequent use (in my next Page Init), after which I override it again.
Problem is my ViewState is null , it doesn't store/remember the value I gave it at the previous page init
Thank you
You can't do that as ViewState is page specific and is actually stored in the HTML of the rendered page. You will need to pass the value via a POST or in the query string or store it in a session or you could cache the value in the asp.net cache which you will be able to access on the other page.
You can use ViewState to transfer data to the same page on Postback.
For setting ViewState:
ViewState["FirstName"] = "SuperMan";
For retrieving ViewState on postback:
string sFirstName = ViewState["FirstName"].ToString();
You can use the Context to Transfer data to the one page to another.
Page1.aspx.cs
this.Context.Items["FirstName"] = "SuperMan";
Page2.aspx.cs
string sFirstName = this.Context.Items["FirstName"].ToString();
You can use the Session variable to preserve the common data which is required almost for every page or across the application for the specific user.
For setting Session:
Session["FirstName"] = "SuperMan";
Applied to your code:
public void Button_Click(object sender, EventArgs e)
{
if (Session["x"] != null)
{
// do processing
// in the end, store value for future use
Session["x"] = myLabel.Text;
}
}
For retrieving Session from any page till the session is valid:
string sFirstName = Session["FirstName"].ToString();
Same way you can use Cookies also, but cookies will be stored on the client.
ViewState just remember value on its page and can't pass value to another page , for use another session state , like Session variable , query string etc
simple use session variable like this
public void Button_Click(object sender, EventArgs e)
{
if(Session["x"] != null)
// use Session["x"] from previous Page Init
//do processing ...
//in the end, store value for future use
Session["x"] = myLabel.Text;
}

Why can't I get the value from textbox?

I've just started learning ASP.NET and I'm facing a problem with getting textbox values. I want to do a simple calculator with only 4 basic operations but what happens is that after I click the + sign and click Go, I see that I didn't store the first number at all. Second number is fine though. Here is a sample of my code.
public partial class deafult : System.Web.UI.Page
{
public TextBox output = new TextBox();
public double temp,tempAdd, calc;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
tempAdd = Convert.ToDouble(output.Text);
output.Text = String.Empty;
}
//User enters another number after clicking Add button then clicks Proc
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
calc = tempAdd + temp;
output.Text = calc.ToString();
}
}
I debugged and tempAdd is always 0 but I get the number in temp. temp variables and calc is defined public.
You essentially have the problem with all of your variables being re-initialized on load of the page. Unlike winforms, web is stateless.
There are ways of persisting state between refreshes, however. The most obvious choice for your application would be to only go to the server once with the both values and what you want to do with them. ie One button click.
However, for personal edification, it may be worth looking up ViewState. This allows you to store values in an array of sorts and retrieve them even after a refresh.
There are also Session and Application level arrays in ASP.NET that work in similar ways.
Every time you call the page (by events) all your properties is initialized.
Try to do all your logic in one event or store your properties in manager / service / db.
In web (Asp.Net) on every postback properties will get cleared, try to use ViewState or Session variables to hold these values. Refer Asp.Net State Management concepts from MS.
Hope this may help you.
Web controls are State less so you should user session sate to hold the first value then do your stuff...
Ex:-
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["tempAdd"] = output.Text;
output.Text = String.Empty;
}
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
string oldval=Session["tempAdd"] != null ?Session["tempAdd"].ToString() :"";
if(oldval!="")
tempadd=Convert.ToDouble(oldval);
calc = tempAdd + temp;
output.Text = calc.ToString();
}

ASP.net page_load doesn't detect session

I have a problem with using session variable in the page_load. I have a page (members.aspx) which is a members area.
If the user isn't logged in, it will display a form asking them to login. The form submits their details, checks if ok then sets session variables if OK. It then reloads the page.
So if the user has authenticated correctly, it sets Session["memberLoggedIn"] = true.
My page_load function then looks like this
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) {
Response.Write("OK");
}
}
There is more code, but essentially, the "OK" should be written. However, it doesn't appear. Even though the session IS set. If I go to the page directly it will then show. It's just for the reloading of the members page from the initial login which stops it.
any ideas?!
======================
the code to set the session is
if (logindetails.Count > 0) {
System.Data.DataRow details = logindetails[0];
Session["memberLoggedIn"] = true;
}
I then just check if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) on all my pages. To be honest it doesn't seem that reliable and I Think sometimes I need to understand the order in which pages are loaded as when I destroy the session on the log out page, some parts still show the logged in features! (but that's another story....)
try this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var user = HttpContext.Current.User;
if(user.Identity.IsAuthenticated)
{
Session["memberLoggedIn"] = true;
Print();
}
}
}
public void Print()
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true)
{
Response.Write("ok");
}
}
This sounds like when you log in you are choosing whether to write "OK" before you have processed the login. In terms of the page's pipeline page_load is before your event handler that you are likely processing the login.
You have various options, the simplest of which could be to move this particular logic to Page_PreRender (if it makes sense to) as at this point your session variable will have been set.

Accessing Controls Values Before Finishing Page_Load

I'm with a problem and want to know if someone can help me.
I'm creating a table with some controls and I want to save all control values in every postback. As the controls are just defined after the page_load, I can't solve my problem this way:
object o;
protected void Page_Load(object sender, EventArgs e)
{
o = createObject();
Create_Table();
if (Page.IsPostBack)
Save_Data();
}
I thought I could execute Save_Data() at the begining of every postback event, but I think that should exist a better way to solve my problem.
Thanks.
Since you want it to be at the page level why not use ViewState? Since o appears to always be set with the same data there probably isn't need to set it more then once, though if you really want to you can remove the if not postback stuff...
protected object o
{
get {
return ViewState["o"];
}
set {
ViewState["o"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) { o = createObject(); }
Create_Table();
if (Page.IsPostBack)
Save_Data();
}
Your variable 'o' will not contain your original value once the postback is done. This is because each request creates a new page object on the server and your member variable values will be lost. It would be better to use the built in 'Session' property to save your data between requests.
See my answer here

Categories

Resources