Page Reload - Keeping Variables
How do I go about when page is reloaded that I make sure the variables I have declared at the top o my class do not get reset开发者_开发问答. IE I have a counter that is originally set at 0 if I use a postback control it resets that variable how do i go about not having this happen in C#?
Are you looking for a value specific to the client or to the server?
If you want something specific to the client use a cookie or session value.
If you are looking something specific to the server use a static class, application or cache value.
Use ASP.Net Session or Cookies. Or you can store their values in hidden fields. You can read about theese and outher option in following article.
Put the value you want to save in a cookie.
if you´re using a postback, not a link, you should save your data into viewstate.
vb
Public Property MyValue() As String
Get
Dim _mv As Object = ViewState("MyValue")
If Not _mv Is Nothing Then
Return _mv.ToString
End If
Return String.Empty
End Get
Set(ByVal value As String)
ViewState("MyValue") = value
End Set
End Property
C#
public string MyValue {
get {
object _mv = ViewState("MyValue");
if ((_mv != null)) {
return _mv.ToString();
}
return string.Empty;
}
set { ViewState("MyValue") = value; }
}
ViewState is saved along PostBacks, if you stay on the current page. For Example if you are on page.aspx and using a <asp:button>
that is clicked each time, you can use Viewstate as a place for saving some of your data, it looks in the page source code like this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4Mzg3MjEyMzdkZNNlI9zvMeIGeUB4MZbJA2gmsHns9IsmAy/c4dQMybXD" />
the viewstate is generated automatically
That data is not persisted on HTTP Requests; you need to persist it in a cookie, hidden control, or manually store it in view state.
If you're manually doing a page counter, consider storing it in session state.
精彩评论