c# - 使用 ViewState 和 ViewStateMode ="Disabled"EnableViewState ="true"

标签 c# asp.net viewstate

我在 aspx 页面中使用 asp.net 和此代码:

public partial class Default : System.Web.UI.Page
{
    string _Name;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            _Name = "Maikel";
            ViewState["Name"] = _Name;
        }
    }

    protected void btnAddName_Click(object sender, EventArgs e)
    {
        if (ViewState["Name"] == null)
        {
            txtName.Text = "Empty";
        }
        else
        {
            txtName.Text = ViewState["Name"].ToString();
        }
    }
}

没关系。并在文本框中显示“Maikel”。 但是当我使用这段代码时:

<%@ Page Language="C#" AutoEventWireup="true" **ViewStateMode="Disabled" EnableViewState="true**" CodeBehind="Default.aspx.cs" Inherits="WebApplication3.Default" %>

ViewState["Name"]!并在文本框中显示“Empty”。为什么?

请帮助我将 ViewStateViewStateMode="Disabled"EnableViewState="true" 一起使用。

编辑:

我使用母版页和(web 来自使用母版页),并在母版页中编写此代码:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" ViewStateMode="Disabled" EnableViewState="true" Inherits="WebApplication3.Site1" %>

和代码 ViewState["Name"] 在代码隐藏页面(来自使用母版页的网络),ViewState 不是空的!!为什么?

最佳答案

在您的情况下,您通过在页面级别设置 ViewStateMode="Disabled" 禁用了整个页面的 ViewState 属性。这就是为什么您在 View 状态中没有得到任何东西的原因。

ASP.NET View State Overview

To disable view state by default for an entire page, set the ViewStateMode attribute of the @ Page directive to Disabled.

Control.ViewStateMode Property (MSDN)

To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.

The ViewStateMode property of a page or a control has an effect only if the EnableViewState property is set to true. If the EnableViewState property is set to false, view state will be turned off even if the ViewStateMode property is set to Enabled.

编辑: 在页面中使用 ViewState。

您可以将所有控件放在一个面板中,并且您可以为该面板将 ViewState 设置为 false。在页面级别启用 ViewStateMode,您将能够在后面的代码中使用 ViewState

对于 MasterPage,您可以在 ContentPlaceHolder 上禁用 ViewState

<asp:ContentPlaceHolder ID="HeadContent" runat="server" EnableViewState="false">
</asp:ContentPlaceHolder>

并在母版页级别启用 ViewStateMode

关于c# - 使用 ViewState 和 ViewStateMode ="Disabled"EnableViewState ="true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14254333/

相关文章:

c# - 临时隐藏或禁用主导航菜单

asp.net - 如何创建通用 StateManagedCollection?

asp.net - 在 SessionPageStatePersister 中保持 ViewState

c# - 在 ViewState 中存储数据表

javascript - 在 javascript 中调用 C# 函数,它在页面加载之前执行。为什么?

asp.net - 远程调试 ASP.NET VSCode

c# - Caliburn Micro,动态加载的 View / View 模型

c# - Web 上的串行端口

c# - 是否可以通过 Dynamic LINQ 进行注入(inject)?

c# - 用于 C# 存储堆栈跟踪的 Oracle 数据类型