当我提交时,为什么我的文本框无法识别值已更改?

时间:2012-09-07 23:30:23

标签: asp.net linq

当我的页面加载时,它会在数据库中查询某些值并用它们填充一些文本框:

protected void Page_Load(object sender, EventArgs e)
{
    tadbDataContext tadb = new tadbDataContext();
    Dictionary<string, string> hexColors = tadb.msp_silentAuctionColors.ToDictionary(t => t.colorDescription, t => t.colorValue);

    tbTextColor.Text = hexColors["textColor"];
    tbAltColor.Text = hexColors["altColor"];
    tbBackgroundColor.Text = hexColors["backgroundColor"];
}

然后我更改了值并尝试重新提交到数据库,方法是单击执行以下操作的按钮:

using (tadbDataContext tadb = new tadbDataContext())
{
    var textColor = tadb.msp_silentAuctionColors.Single(x => x.colorDescription == "textColor");

    var altColor = tadb.msp_silentAuctionColors.Single(x => x.colorDescription == "altColor");
    var backgroundColor = tadb.msp_silentAuctionColors.Single(x => x.colorDescription == "backgroundColor");

    textColor.colorValue = tbTextColor.Text;
    altColor.colorValue = tbAltColor.Text;
    backgroundColor.colorValue = tbBackgroundColor.Text;

    tadb.SubmitChanges();
}

回发的值是原始值(未更改)。如果我注释掉在加载时填充文本框的行,它就可以正常工作。

1 个答案:

答案 0 :(得分:3)

这是因为您没有将数据绑定内容包装在IsPostBack中 - 请检入Page_Load。因此,您始终使用旧数据库覆盖已更改的值。

所以你必须这样做:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        tadbDataContext tadb = new tadbDataContext();
        Dictionary<string, string> hexColors = tadb.msp_silentAuctionColors.ToDictionary(t => t.colorDescription, t => t.colorValue);

        tbTextColor.Text = hexColors["textColor"];
        tbAltColor.Text = hexColors["altColor"];
        tbBackgroundColor.Text = hexColors["backgroundColor"];
    }
}