DetailsView - ItemUpdating中不更改的值

时间:2015-12-18 13:48:46

标签: c# asp.net .net webforms

我将DetailsView绑定到一个对象。调用ItemUpdating时(单击更新时)OldValues为空,NewValues包含旧值(与更新前相同)。

<asp:DetailsView ID="CustomerDetailsView" runat="server"
    DefaultMode="Edit"
    AutoGenerateRows="false"
    OnItemUpdating="CustomerDetailsView_ItemUpdating"
    >
    <Fields>
        <asp:BoundField DataField="LastName" HeaderText="Last name" ReadOnly="True" />
        <asp:BoundField DataField="FirstName" HeaderText="First name" ReadOnly="True" />
        <%-- Other fields ... --%>
        <asp:CommandField ShowEditButton="true" />
    </Fields>
</asp:DetailsView>

代码背后:

private Customer customer;
protected void Page_Load(object sender, EventArgs e)
{
    using (var context = new CustomersContext())
    {
        customer = context.Logins.First();
    }

    CustomerDetailsView.DataSource = new List<Customer>() { customer };
    CustomerDetailsView.DataBind();
}

protected void CustomerDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
    // e.OldValues.Count == 0
    // e.NewValues["FirstName"] - is same as taken from database
}

2 个答案:

答案 0 :(得分:2)

请参阅此答案:OldValues collection in event "ItemUpdating" of DetailsView is always empty

看来这只有在使用绑定到数据源控件的DataSourceID属性时才有效。

答案 1 :(得分:0)

愚蠢的我,每次重新加载页面时我都会设置新的DataSource,即使它是回发的。

应该是:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        using (var context = new CustomersContext())
        {
            customer = context.Logins.First();
        }

        CustomerDetailsView.DataSource = new List<Customer>() { customer };
        CustomerDetailsView.DataBind();
    }
}

无法看到OldValues但NewValues看起来是正确的。