下拉列表绑定和视图状态的问题 [英] The problem of dropdown list binding and the view state

查看:66
本文介绍了下拉列表绑定和视图状态的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我们都知道绑定下拉列表时视图状态非常巨大的问题。几周前我搜索了它,我找到的解决方案是覆盖OnInit方法。以此为例:

Hello all,

We all know the problem of very huge view state when binding the dropdownlist for example. Few weeks ago I searched for it and the solution I found was to override OnInit method. Take this for example:

protected override void OnInit(EventArgs e)
{
    ddlCustomers.DataSource = SystemData.GetAllCustomers();
    ddlCustomers.DataTextField = "CustomerName";
    ddlCustomers.DataBind();
    ddlCustomers.Items.Insert(0, new ListItem("Select Customers", "-1"));
    base.OnInit(e);
}



使用此代码,视图状态只有3到4行(好吧,因为我有很多控件:D)



有人可以解释一下这是如何工作的吗?我对ASP.net页面生命周期有点熟悉,但是无法弄清楚它是如何工作的。


With this code the view state is only 3 to 4 lines (Well maybe because of a lot of controls I have :D )

Can some explain how this works ? I'm little bit familiar with ASP.net page life cycle but just can't figure out how this works.

推荐答案

如果你绑定你会得到更好的结果 control Init 事件中的列表,而不是页面。

You'll get better results if you bind the list in the Init event of the control, rather than the page.
protected void ddlCustomers_Init(object sender, EventArgs e)
{
    var ddl = (DropDownList)sender;
    ddl.DataSource = SystemData.GetAllCustomers();
    ddl.DataTextField = "CustomerName";
    ddl.DataBind();
    ddl.Items.Insert(0, new ListItem("Select Customers", "-1"));
}





这样做的原因是控件的 Init 在控件开始跟踪对其 ViewState 的更改之前触发事件。因此,控件只是假设每次加载页面时都会重新创建列表,而不是将项目列表存储在 ViewState 中。



您想在控件的 Init 事件中执行此操作,而不是页面的 Init 事件,由于事件的引发方式:



The reason this works is that the control's Init event is fired before the control starts tracking changes to its ViewState. As a result, rather than storing the list of items in ViewState, the control simply assumes that the list will be recreated every time the page is loaded.

You want to do this in the control's Init event rather than the page's Init event, due to the way the event is raised:

internal virtual void InitRecursive(Control namingContainer)
{
    // Pseudo-code:
    if (HasControls)
    {
        foreach (Control child in Controls)
        {
            child.UpdateNamingContainer(namingContainer);
            child.GenerateAutomaticID();
            child.Page = this.Page;

            child.InitRecursive(namingContainer);
        }

        Controls.SetCollectionReadOnly();
    }

    ApplySkin(Page);
    OnInit(EventArgs.Empty);
    TrackViewState();
}



Init 事件是一个冒泡事件;在父控件上升之前,它会在子控件上引发。当页面的 Init 事件被引发时,控件已经跟踪视图状态。


The Init event is a bubbling event; it's raised on the child controls before it's raised on the parent. By the time the page's Init event is raised, the control is already tracking view-state.


这篇关于下拉列表绑定和视图状态的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆