【问题标题】:Viewstate null on postback回发时的 Viewstate null
【发布时间】:2011-06-09 17:53:00
【问题描述】:

所以我的页面上有一个列表框和一些文本字段。通过文本字段,我可以将一个项目添加到我的列表框中(单击按钮,它将它添加到一个私有列表中,然后将其设置为 ViewState 并且列表再次被数据绑定)。我的列表框也在按钮的 Click 事件上触发的更新面板中。问题:我的 Viewstate 在回发时保持为空,因此每次都会重置。

一些代码:

private const string VIEW_INGREDIENTS = "IngredientsList";
        private const string VIEW_LANGUAGE = "CurrentLanguage";
        private List<IngredientData> _ingredientsList;

protected void Page_PreInit(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (ViewState[VIEW_INGREDIENTS] != null)
                {
                    _ingredientsList = (List<IngredientData>) ViewState[VIEW_INGREDIENTS];
                }

            }
            else
            {
                // prepare ingredient lists
                _ingredientsList = new List<IngredientData>();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            lstIngredients.DataSource = _ingredientsList;
            lstIngredients.DataTextField = "Text";
            lstIngredients.DataValueField = "Name";
            lstIngredients.DataBind();
        }

protected void btnAddIngredient_Click(object sender, EventArgs e)
        {
            _ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });

            ViewState[VIEW_INGREDIENTS] = _ingredientsList;
            lstIngredients.DataSource = _ingredientsList;
            lstIngredients.DataBind();
        }

【问题讨论】:

    标签: asp.net listbox postback viewstate


    【解决方案1】:

    您在 PreInit 期间使用 vewstate 吗?稍后在 PreLoad 期间尝试检查一下。

    【讨论】:

    • 这似乎解决了它!谢谢!
    【解决方案2】:

    检查页面是否有EnableViewState="true":

    <%@ Page Language="C#" EnableViewState="true" ...
    

    并验证web.config 中的站点范围设置:

    <pages enableViewState="true" enableViewStateMac="true" ... />
    

    现在 ASP.NET 已经为列表控件内置了视图状态,所以我想知道您为什么要为它编写自定义代码。默认视图状态应该适用于您要完成的任务。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 2023-04-02
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多