我对.NET不太熟悉,但我想将一个简单的值(1到1000之间的数字,这是特定div
的高度)保存到视图状态,并在更新面板重新加载(在标记某处或使用javascript)。最简单的方法是什么?
This page给了我以下代码:
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";
但是,我不清楚在何处或如何访问示例strColor。
由于这是在后面的代码中,Response.Write
甚至会吐出那些代码?我尝试这段代码时找不到它。我如何使用javascript设置该值,而不是在后面的代码中设置它?
答案 0 :(得分:6)
您可以将div设置为服务器控件,如下所示:
<div id="yourdiv" runat="server" ...
当页面回发时;只需通过设置其属性来设置它的高度;例如:
yourDiv.Attributes("style","height:"+height_read_from_ViewState+"px;");
或者,您可以使用隐藏字段在客户端存储高度,并在服务器端读取隐藏字段的值以设置div的高度。
<asp:hiddenfield id="hdnHeight" runat="server" />
您可以在Javascript中设置高度:
function setHeight(value)
{
document.getElementById('<%=hdnHeight.ClientID').value=value;
}
在服务器端回帖:
yourDiv.Attributes("style","height:"+hdnHeight.Value+"px;");
答案 1 :(得分:1)
我会将strColor更改为属性,并使用viewstate作为属性的后备存储。
public string strColor
{
get
{
return ViewState["strColor"];
}
set
{
ViewState["strColor"] = value;
}
}
然后你会像任何其他财产一样使用它:
if (Page.IsPostBack)
{
// Retrieve and display the property value.
Response.Write(strColor);
}
else
// Save the property value.
strColor = "yellow";