c# - 如何在 ASP.NET Web 表单类中处理类字段?

标签 c# .net asp.net viewstate

考虑一个带有关联代码文件 (aspx.cs) 的 Web 表单 (aspx)。

例如,在代码文件中,我们有以下内容:

public partial class MyPage : System.Web.UI.Page {

   int myint;
   string mystring;

   public void Page_Load(object sender, EventArgs e) {
      ...
      if (!this.IsPostBack) {
         this.myint = 2;
         this.mystring = "Hello";
      }
      ...
   }

}

每次回发页面时我都可以期望有这两个变量吗?我的意思是:页面类字段是否保留为 Web 表单状态的一部分?

谢谢

最佳答案

不,这些对象将在 Page-Lifecycle. 结束时被释放 如果你想将它们保存在 ViewState 中,你必须 add them to it .

ViewState中需要存储的对象必须是serializable .

在 ViewState 中存储简单数据类型

Like most types of state management in ASP.NET, view state relies on a dictionary collection, where each item is indexed with a unique string name. For example, consider this code:

ViewState["ViewStateVariableName"] = 1;

This places the value 1 (or rather, an integer that contains the value 1) into the ViewState collection and gives it the descriptive name ViewStateVariable. If there is currently no item with the name ViewStateVariable, a new item will be added automatically. If there is already an item indexed under this name, it will be replaced.

You can access this variable anywhere within the page/control where the viewstate variable has been added. When retrieving a value, you use the key name.

int number = (int) ViewState["ViewStateVariable"];

You also need to cast the retrieved value to the appropriate data type. This is because the ViewState collection stores all items as generic objects which also give you the flexibility to store any type of basic data types in it. In fact, you can even store your custom objects in the view state.

在 View 状态中存储对象

You can store your own objects in view state just as easily as you store numeric and string types. However, to store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization. If your objects aren't serializable (and by default they aren't), you'll receive an error message when you attempt to place them in view state.

关于c# - 如何在 ASP.NET Web 表单类中处理类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409179/

相关文章:

c# - 我可以创建一个可以修改用户界面并且可以中止的线程吗?

asp.net - UseJwtBearerAuthentication 返回 401

asp.net - Razor 递归树形菜单结构

c# - 从 MDI 容器窗体中删除图标

.net - .NET 4.0 中的 Microsoft.csharp.dll 是什么

c# - C到C#代码转换——数组作为参数

asp.net - 如何为 WebApi 管道外的错误返回 JSON?

asp.net - SignalR - 跨应用程序使用

c# - 为什么 HTML.TextArea 之前需要一个@?

c# - 如何为复杂类型设置 DataKeyNames?