0

我在这种情况下遇到了困难,希望有人可以帮助我澄清我缺少步骤/逻辑的地方。我尝试在线搜索,但找不到解决此问题的示例。

我们正在设置一个搜索页面,当第一次加载时会显示一堆选项(例如,文本框、复选框等)。用户将填写表格并将表格提交给自己。发回后,页面将使用用户选项针对数据库构建并运行 SQL 查询(例如,SELECT ID FROM Customers WHERE Company = 'Acme' AND AmtDue = 3),然后显示结果。这部分工作正常。

崩溃的部分是当我尝试添加分页时。结果集是绑定到Repeater 的DataTable。我正在使用 PagedDataSource 添加分页。分页适用于第一页,但对于后续页面,它不起作用。基本上,不是返回请求结果的下一页(例如,SELECT ID FROM Customers WHERE Company = 'Acme' AND AmtDue = 3),而是返回的结果是附加用户搜索选项之前的 SQL 查询(例如,SELECT ID FROM顾客)。

我认为我的基本问题是我不确定如何区分正常的 Page.IsPostBack 并通过结果进行分页。这导致问题的原因是因为我不想重新收集表单数据、重建查询和重新查询数据库。

我在网上找到的示例涉及每次加载页面时都会重新构建的 DataTable 的分页(例如,Not Page.IsPostBack)。

这是我们代码的粗略概述:

Public dtCustomers As DataTable = New DataTable()
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles Me.Load
    ' When the page first loads, show the search form with search options.
    If Not Page.IsPostBack Then
        ShowSearchForm()
    ' Once the form is submitted, show the search results.
    Else
        ' ----------------------------------------
        ' This is the part that I'm having trouble with. How do I skip the following two steps (GatherFormData() and BuildDT()) when the user requests a subsequent page?
        GatherFormData()
        dtCustomers = BuildDT()
        ' ----------------------------------------
        BindData()
    End If
End Sub
Sub BindData()
    Dim objPDS As PagedDataSource = New PagedDataSource()
    objPDS.DataSource = dtCustomers.DefaultView
    objPDS.AllowPaging = True
    objPDS.PageSize = intNumPerPage
    objPDS.CurrentPageIndex = Me.ViewState("_CurrentPage")
    rptSearchResults.DataSource = objPDS
End Sub
' Subroutine called when the previous page button is pressed.
Sub GoToPrevPage()
    ' Set viewstate variable to the previous page.
    Me.ViewState("_CurrentPage") -= 1
    BindData()
End Sub
' Subroutine called when the next page button is pressed.
Sub GoToNextPage()
    ' Set viewstate variable to the next page.
    Me.ViewState("_CurrentPage") += 1
    BindData()
End Sub

注意:我知道必须将 DataTable 放入缓存或会话变量中,但尚未确定最佳方法。

请原谅代码大纲,但实际代码量很大,因此简化是为了更容易找到问题的核心。

让我知道是否有任何不清楚的地方。提前致谢!

4

1 回答 1

0

我假设您要将数据存储在会话/缓存中(我更喜欢后者,但可能有将其存储在会话中的用例) - 您可以将密钥存储在视图状态中,并且密钥的存在可能是用于确定回发是否用于分页。例如,

if (ViewState["dataKey"] == null)
{
   // first form submittal, do the search
   GatherFormData();
   dtCustomers = BuildDT();
   // store it in cache
   ViewState["dataKey"] = Guid.NewGuid().ToString();  // create a key
   Cache.[ViewState["dataKey"].ToString()] = dtCustomers;  // TODO use Add method to control expiration etc
}

重置搜索(或类似条件)时清除视图状态很重要

最后,也可以从数据库/数据存储中进行分页(例如,使用 SQL Server 中的排名函数),这样您就不必将搜索结果存储到会话/缓存中,而是在每次回发。当完整的结果集大小可能很大时,这种方法很有用。

于 2013-01-15T09:52:37.840 回答