1

我的页面中有一个 asp 占位符,我动态地将“行”插入其中,其中每一行都是一个用户控件。

如果请求是 GET 请求,我会从数据库中加载数据并根据需要填充尽可能多的用户控件。我还将控制实例添加到会话内容中。

如果请求是 POST 请求,我首先通过查看 Page_Load() 内部的会话内容来重新创建控件。之后,每个按钮的处理程序可以做任何需要做的额外工作,例如添加新行(到占位符、会话和 DB)、删除行(从占位符、会话和 DB)或更新现有行。

我在这里面临几个问题:

  1. 删除行时,有时即使删除了正确的行,删除后屏幕上也会显示错误的数据。这是危险的,因为对于进一步的删除,我们不知道哪些行会受到影响。
  2. 添加新行时,有时其中一个现有行将包含错误的数据(特别是来自另一现有行的数据)

我该如何解决这些问题?我什至很难诊断问题。这些是常见问题吗?我只是这样做完全错误吗?有什么更好的方法来实现这一点?

4

1 回答 1

1

I've had issues like this before. I fixed them by:

  • When you instantiate your usercontrol before you put it into the placeholder it needs to have the same ID as it did before postback (ie when you first created it). I do something like "usr_" + <db record id>. This ensures its the same ID no matter what order it gets loaded, what records get deleted, etc. This is probably the most important thing to do, because if you don't assign it ID's .NET will assign them for you -- and they are assigned in the order they show up in the control collection which means you potentially will have the wrong info in the wrong user control (which you described in your question).
  • Not using the session to store info about the page. Once the ID issues were fixed people were still having issues if the opened up two tabs of the same page.

Something along these lines:

using (SqlConnection c = new SqlConnection(DB_STRING))
{
    c.Open();
    String sql = @"
        SELECT *
        FROM yourTable
        ORDER BY ID;";
    using (SqlCommand cmd = new SqlCommand(sql, c))
    {
        using (SqlDataReader d = cmd.ExecuteReader())
        {
            while (d.Read())
            {
                UserControl uc = (UserControl)new UserControl().LoadControl("~/path/to-your-control/YourControl.ascx");
                uc.ID = "usr_" + d["ID"];
                plcHolderRows.Controls.Add(uc);
            }
        }
    }
}
于 2013-09-26T21:20:20.933 回答