I am attempting to create a simple "recover" button for a field of values. For some reason, strings stored in ViewState do not show. I followed a tutorial so I really don't know what I did wrong, I also searched the web for an answer, the main issue for many being that they didn't have ViewState enabled in the page, which I didn't also so I added it (but the button still doesn't work). As for the way I wrote the code, or how I use ViewState, I was unable to find an issue. Any help would be appreciated.
So this is what I have in the Contact.aspx page:
<%@ Page Title="" Language="C#" EnableViewState="true"/*...*/
<asp:TextBox class="form-control" id="usr" runat="server"/>
<asp:Button Text="Send" ID="buttonSend" runat="server"
onclick="buttonSend_Click"/>
<asp:Button Text="Recover" id="buttonRecover" runat="server"
onclick="buttonRecover_Click"/>
And this is the code behind, in Contact.aspx.cs:
protected void buttonSend_Click(object sender, EventArgs e)
{
ViewState["name"] = Request.Form["usr"];
usr.Text=string.Empty;
}
protected void buttonRecover_Click(object sender, EventArgs e)
{
usr.Text = Convert.ToString(ViewState["name"]);
}
The problem is that Request.Form["usr"]
does not exist. The ID of a control is not the same as the Form Post Key (which is the name
of an input control).
So either use
ViewState["name"] = Request.Form[usr.UniqueID];
Or the recommended way
ViewState["name"] = usr.Text;