简体   繁体   English

在动态向该表添加行后,为什么我的HTML表行会丢失视图状态?

[英]Why does my HTML table row loses view state after dynamically adding rows to this table?

I have a simple HTML table like this: 我有一个简单的HTML表格,如下所示:

<table id="table" runat="server">
    <tr>
        <td>
            <asp:Label runat="server" Text="Column1" />
        </td>
    </tr>
    <tr id="tr_someId" runat="server">
        <td>
            <asp:Label ID="lb_someId" runat="server" />
        </td>
    </tr>
</table>

On every request I add dynamic rows between ( rowIdx = 1 ) the existing rows like: 在每个请求中,我rowIdx = 1 )现有行之间添加动态行例如:

protected override void OnLoad( EventArgs e )
{
    base.OnLoad( e );

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( CreateLabelCell( something ) );

        table.Rows.Insert( rowIdx++, tr );
    }
}

Now, I wonder, why my lb_someId-Label loses its text on a PostBack? 现在,我想知道为什么我的lb_someId-Label在回发后丢失其文本? I think it should not happen because it is a fixed control. 我认为这不应该发生,因为它是固定控件。 It does not lose its text when I comment the table.Rows.Insert( rowIdx++, tr ); 当我注释表时,它不会丢失其文本table.Rows.Insert( rowIdx++, tr ); line out. 线路输出。

Thank you in advance! 先感谢您!

The reason that the value of the label gets lost is because it is part of a table to which new rows are being added in the OnLoad event. 标签值丢失的原因是因为它是表的一部分,在OnLoad事件中向该表添加了新行。 At this point in the lifecycle dynamically added controls are not being tracked anymore. 在生命周期的这一点上,不再跟踪动态添加的控件。 The table tracks its viewstate as a whole, including some info about the label. 该表将整体跟踪其视图状态,包括有关标签的一些信息。 If the label was outside of the table, there wouldn't have been a problem. 如果标签在桌子外面,那不会有问题。 See MSDN: Understanding ASP.NET View State . 请参见MSDN:了解ASP.NET视图状态

Move the code to OnInit . 将代码移至OnInit

protected override void OnInit(EventArgs e)
{   
    base.OnInit(e);

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( CreateLabelCell( something ) );

        table.Rows.Insert( rowIdx++, tr );
    }
}

Alternativelly, only moving the foreach loop to OnInit would suffice. 或者,仅将foreach循环移动到OnInit就足够了。

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }
}

protected override void OnInit(EventArgs e)
{   
    base.OnInit(e);

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( new HtmlTableCell { InnerText = something } );

        table.Rows.Insert( rowIdx++, tr );
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM