ViewState doesn't remember value from previous page init - c#

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;
}

Related

ASP.NET const string session key lost on PostBack

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.

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.

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();
}

how to avoid re initialization of session value after redirecting to same page

I have intialized some session variables in page load method to zero. Then I am modifying them in button press method. I am using one session variable as a counter but when I am redirecting the page to the same page, the variables are intialized again. Please help me to prevent this re-initialization. I don't want to use static variables.
The scenario is-
protected void Page_Load(object sender, EventArgs e)
{
session["counter"] = 0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count = (int)session["counter"];
count++;
session["counter"] = count;
response.redirect("same page");
}
Assuming you just want to check for a non set session variable and if so, set it to zero, then you could just do:
protected void Page_Load(object sender, EventArgs e)
{
if(session["counter"] == null) {
session["counter"] = 0;
}
}
There are also a range of client side options you could use, depending on the situation.
Use
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
session["counter"]=0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=(int)session["counter"];
count++;
session["counter"]=count;
//remove response.redirect("same page");
}
Your buuton is server side so your page will postback so you do not need to use response.redirect("same page");
If you are indeed redirecting, and not posting back, just check, on page load, if your initial variable has been set? If not, set it. If it is set, ignore setting it.
'set initial value
if session("counter") is nothing then
session("counter") = 0
end if
If you are posting back, you could also use the above, or you could:
If not isPostBack then
session("counter") = 0
end if
You can move that initialisation to a different page. Instead of directly jumping to your "same page" from another part of your application, julp to an "initializer" instead. That page initializes your session variables and immediately redirects to your "same page".
Your "Button_Click" still redirects to "same page", bypassing that initialisation.

ASP.NET C# - How to retain value after Response.Redirect

I'm working in ASP.NET c# application.
I came to a part where I need to retain some value after response.redirect to the same page without using additional QueryString or Session, because Session more or less may burden the server's performance even just a small value.
Below is my code fragment:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string id = ddl.SelectedValue;
string id2 = ddl2.SelectedValue;
Response.Redirect("http://sharepoint2007/sites/home/Lists/CustomList/DispForm.aspx?ID=" + id);
}
I wanted to retain the value id2 after the Response.Redirect, I've tried ViewState but seem like after the redirect, it treat the page as new page and ViewState value gone.
Update:
My intention to retain the value after redirect is wanted to bind back the dropdownlist selected value.
Please help.
Thank you in advanced.
using cookies will do the trick:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string id = ddl.SelectedValue;
string id2 = ddl2.SelectedValue;
HttpCookie cookie = new HttpCookie("SecondId", id2);
Response.Cookies.Add(cookie);
Response.Redirect("http://sharepoint2007/sites/home/Lists/CustomList/DispForm.aspx?ID=" + id);
}
protected void OnLoad(object sender, EventArgs e)
{
string id2 = Request.Cookies["SecondId"];
//send a cookie with an expiration date in the past so the browser deletes the other one
//you don't want the cookie appearing multiple times on your server
HttpCookie clearCookie = new HttpCookie("SecondId", null);
clearCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(clearCookie);
}
Make use of Session variable will do for you
Code for you
Session["id2"] = ddl2.SelectedValue;
as you are redirecting from one page to another page viewstate is not going to help you , Session varialbe can able to store value till the user logout of site or till session ends, ViewState is helpfull when you are doing autopostback to your page
or
if possible you can attach id2 variable in querystring only as you are doing with id1 variable
besides session, query string, you can also use cookie, application variable and database to persist your data.
You can achieve it using Session or by QueryString
By Session
In your first page:
Session["abc"] = ddlitem;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String cart= String.Empty;
if(!String.IsNullOrEmpty(Session["abc"].ToString()))
{
xyz= Session["abc"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
private void button1_Click(object sender, EventArgs e)
{
String abc= "ddlitem";
Response.Redirect("Checkout.aspx?ddlitemonnextpage" + abc)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string xyz= Request.QueryString["ddlitemonnextpage"].ToString();
// do Something();
}

Categories

Resources