murday1983
murday1983

Reputation: 4026

Remove Session Value If I Delete Value From Field And Re-Submit Form

I have an asp.net webform that stores details entered in the session and then displays all the details on a confirmation page later on. All these works are fine. If the user navigates back to the page, the details are still displayed but the issue i'm having is that:

User Scenario

User enter's details in a none mandatory field and continues. This value is displayed on the confirmation page as expected. User then goes back to the page and deletes the value in the none mandatory field and continues BUT the value deleted is still deleted on my confirmation page.

I have debugged it and at first I can see that the field is empty. But when the code drops back into my submitbutton_click, it re-adds it.

The current code that I have is displayed below:

Code

protected void Page_Load(object sender, EventArgs e)
{            
     if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
     {
          Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
     }
}

protected void Step01SubmitButton_Click(object sender, EventArgs e)
{
     Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
}

Upvotes: 2

Views: 1043

Answers (1)

Phil
Phil

Reputation: 3756

From what I can discern from your post it seems that when you update the Step01AddressBuildingname field to be blank and click on submit, this does not clear down the session value as expected. If so it's because you're not handling the post back in you page_load event. In asp.net webforms postbacks occur when a form is submitted to the server, in this scenario you just want to handle the form submission and not load the page as standard. You do this by checking the IsPostBack property on the page.

In your code, because you're not checking this property, tep01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString(); is getting executed before the submit button's click event handler - hence the value doesn't get deleted. Try this

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) { 
            if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
            {
                Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
            }
        }
    }

    protected void Step01SubmitButton_Click(object sender, EventArgs e)
    {
        Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
    }

Upvotes: 1

Related Questions