Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting viewstate on postback

I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
    }
}

private string YourName
{
    get { return (string)ViewState["YourName"]; }
    set { ViewState["YourName"] = value; }
}


protected void btnSubmit_Click(object sender, EventArgs e)
{
    YourName = txtName.Text;

}

Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC:

<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>

PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.

like image 824
Espo Avatar asked Sep 03 '08 10:09

Espo


People also ask

Where the ViewState is stored after the page postback?

Where the viewstate is stored after the page postback? ViewState is stored in a hidden field on the page at client side. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.

Why ViewState is not used in MVC?

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method. Once the controller method has been called, what you do with those values is up to you.

How can we store and retrieve values ViewState?

If you need to store extraneous information in ViewState, you can get and set data in ViewState like you would any other key/value collection: //store value in viewstate ViewState["someValue"] = "Foo"; //retrieve value from viewstate string someValue = ViewState["someValue"]. ToString();


1 Answers

Page_Load fires before btnSubmit_Click.

If you want to do something after your postback events have fired use Page_PreRender.

//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
    if (Page.IsPostBack)
        lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}

The basic order goes:

  • Page init fires (init cannot access ViewState)
  • ViewState is read
  • Page load fires
  • Any events fire
  • PreRender fires
  • Page renders
like image 90
Keith Avatar answered Sep 21 '22 19:09

Keith