Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a value to and reading from the viewstate

I'm not too familiar with .NET, but I want to save a simple value (a number between 1 and 1000, which is the height of a particular div) to the viewstate and retrieve it when the update panel reloads (either in the markup somewhere or with javascript). What is the simplest way to do this?

This page gives me the following code:

string strColor;
if (Page.IsPostBack)
{
   // Retrieve and display the property value.
   strColor = (string)ViewState["color"];
   Response.Write(strColor);
}
else
   // Save the property value.
   ViewState["color"] = "yellow";

However, I'm not totally clear on where or how to access the example strColor.

Since this is in the code behind, where will Response.Write even spit that code out? I couldn't find it when I tried this code. And how do I use javascript to set that value, instead of setting it in the code behind?

like image 656
brentonstrine Avatar asked Aug 02 '12 17:08

brentonstrine


2 Answers

You can simply set the div as a server control as so:

<div id="yourdiv" runat="server" ...

And when the page posts back; simply set it's height by setting its attributes; for example:

yourDiv.Attributes("style","height:"+height_read_from_ViewState+"px;");

Or, you can store the height on the client side, using a Hidden field and reading that hidden field's value on the server side to set the div's height.

<asp:hiddenfield id="hdnHeight" runat="server" />

You set the height in Javascript as so:

function setHeight(value)
{
  document.getElementById('<%=hdnHeight.ClientID').value=value;
}

And on post back on server side:

yourDiv.Attributes("style","height:"+hdnHeight.Value+"px;");
like image 165
Icarus Avatar answered Sep 22 '22 19:09

Icarus


I would change strColor to a property and use the viewstate as a backing store for the propery.

public string strColor 
{
    get
    {
        return ViewState["strColor"];
    }
    set
    {
        ViewState["strColor"] = value;
    }

}

And then you would use it like any other property:

if (Page.IsPostBack)
{
   // Retrieve and display the property value.
   Response.Write(strColor);
}
else
   // Save the property value.
   strColor = "yellow";
like image 30
Jeff Avatar answered Sep 21 '22 19:09

Jeff