我的asp.net页面中有一个listview,它绑定到一个数据表,这是从后面的代码加载页面完成的。我正在尝试使用SelectedItemTemplate,但是从试验和错误中,如果控件在回发后数据绑定,我只能使用它。这工作正常,但问题是这意味着每次回调数据库,即使没有数据发生更改,这会使用户体验变慢。因此我的问题是:是否可以选择列表视图中的项目,显示SelectedItemTemplate,而无需对数据进行完全重新绑定。我不介意回服务器,我只是想避免对数据库进行不必要的调用。这是我的标记:
<asp:ListView ID="lv" runat="server" DataKeyNames="id" EnablePersistedSelection="True">
<LayoutTemplate>
<ul>
<li runat="server" id="itemPlaceholder"></li>
</ul>
</LayoutTemplate>
<ItemTemplate>
<div id="Div1" runat="server">
<!-- My Item Controls -->
</div>
</ItemTemplate>
<SelectedItemTemplate>
<div id="Div2" runat="server">
<!-- My Selected Item Controls -->
</div>
</SelectedItemTemplate>
</asp:ListView>
这是我的代码隐藏:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'Load the data on the first page load
LoadEvents()
End If
End Sub
Protected Sub LoadEvents()
'Some code to get data from DB and bind to listview control
End Sub
Protected Sub lv_SelectedIndexChanging(sender As Object, e As ListViewSelectEventArgs) Handles lv.SelectedIndexChanging
lv.SelectedIndex = e.NewSelectedIndex
LoadEvents()
End Sub
提前致谢!
答案 0 :(得分:0)
您可以将DataTable
保存在Session
中,然后在LoadEvents
中进行检索。只有在最初加载时,它才会来自DataBase。 LoadEvents
子可能如下所示:
Private Sub LoadEvents(Optional ByVal refresh As Boolean = False)
Dim myTable As DataTable = New DataTable
If refresh = True Then
'Code to get data from database
'and fill myTable Goes here
' ... ... ...
Session("MyTable") = myTable
Else
If Not Session("MyTable") Is Nothing Then
myTable = DirectCast(Session("MyTable"), DataTable)
End If
End If
lv.DataSource = myTable
lv.DataBind()
End Sub
当没有参数调用它时,它将从Session获取数据。在Page_Load
中,我们需要使用true
调用它来从DataBase获取新数据:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'Load the data on the first page load
'Called the sub with parameter to get fresh data from db
LoadEvents(true)
End If
End Sub