C# 将值保存到视图状态并从视图状态读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11782654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a value to and reading from the viewstate
提问by brentonstrine
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?
我对 .NET 不太熟悉,但我想将一个简单的值(1 到 1000 之间的数字,这是特定的高度div)保存到视图状态,并在更新面板重新加载时检索它(在标记中)某处或使用javascript)。什么是最简单的方法来做到这一点?
This pagegives 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.
但是,我并不完全清楚在哪里或如何访问示例 strColor。
Since this is in the code behind, where will Response.Writeeven 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?
既然这是在后面的代码里,Response.Write那代码还往哪里吐呢?当我尝试这段代码时,我找不到它。以及如何使用 javascript 设置该值,而不是在后面的代码中设置它?
采纳答案by Icarus
You can simply set the div as a server control as so:
您可以简单地将 div 设置为服务器控件,如下所示:
<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.
或者,您可以在客户端存储高度,使用 Hidden 字段并在服务器端读取该隐藏字段的值来设置 div 的高度。
<asp:hiddenfield id="hdnHeight" runat="server" />
You set the height in Javascript as so:
您在 Javascript 中设置高度如下:
function setHeight(value)
{
document.getElementById('<%=hdnHeight.ClientID').value=value;
}
And on post back on server side:
并在服务器端回传:
yourDiv.Attributes("style","height:"+hdnHeight.Value+"px;");
回答by Jeff
I would change strColor to a property and use the viewstate as a backing store for the propery.
我会将 strColor 更改为一个属性,并将视图状态用作该属性的后备存储。
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";

