I’m having a hard time understanding why the following code doesn’t work. I’m sure it’s something remedial that I’m missing or not understanding. I currently have a page that asks for user input. If, based on the input and logged in user, I find data from this page already in the database, I need to update the existing records rather than creating new ones, so I set a class-level bool to true. The problem is, when MyNextButton is clicked, PreviouslySubmitted is still false. So, I’m not sure how to make the value of this variable persist. Any advice is appreciated, thanks.
public partial class MyForm : System.Web.UI.Page
{
private bool PreviouslySubmitted;
protected void Page_Load(object sender, EventArgs e)
{
MyButton.Click +=
(o, i) =>
{
q = from a in db.TableA
where (a.SomeField == SomeValue)
select a;
if(q.Any())
{
PreviouslySubmitted = true;
//populate the form's fields with values from database for user to revise
}
}
MyNextButton.Click +=
(o, i) =>
{
//the value of PreviouslySubmitted is false at this point,
//even if I made sure it was set to true the previous postback
if(PreviouslySubmitted)
{
//update database
}
else
{
//insert into database
}
}
Declare the previouslySubmitted variable as a static.
Important update
I’m sorry, I haven’t check “based on the input and logged in user” part of the question.
Why it works is simple: there is no shared state between requests and postbacks of the page — it’s a lack of HTTP protocol.
So, state of the page controls is being rebuilt on every request using the ViewState mechanism, but your own objects, fields and variables are not. Every page request (visitor) has it’s own instance of MyForm class, but static variables are common to all of them. So, remove the static keyword and use ViewState/SessionState to store the value of PreviouslySubmitted variable per user.