我有一个非常奇怪的问题。我正在创建一个网页,从数据库中检索链接列表并显示它们。我检索记录并将它们加载到对象列表中。但是,当我稍后遍历该列表时,我将显示重复的项目。
查看结果的页面为http://myhacc.azurewebsites.net/testlinks.aspx
每个链接应该只有1个,你可以看到每个链接中有2个。我不知道为什么。我已经超过了我的逻辑10次。
我正在使用在microsoft azure上运行的Microsoft SQL Server 网页也作为网络应用程序托管在microsoft azure上。
我检查了我的数据库,数据库中没有重复的条目。 数据库的结构如下
表:myportal_lcat 字段:id - 整数 字段:名称 - 文本
表:myportal_lhref 字段:catid - 整数 字段:dname - 文本 字段:href - text
代码如下
<%@ Page Title="" Language="VB" MasterPageFile="~/Main.master" %>
<script runat="server">
Private oCon As Data.SqlClient.SqlConnection
Private oCon2 As Data.SqlClient.SqlConnection
Private oCatCom As New Data.SqlClient.SqlCommand
Private oCatRead As Data.SqlClient.SqlDataReader
Private oItemCom As New Data.SqlClient.SqlCommand
Private oItemRead As Data.SqlClient.SqlDataReader
Private liLinks As New List(Of linkItem)
Private Sub Page_Load() Handles Me.Load
oCon = New Data.SqlClient.SqlConnection("Server=xxxx,1433;Database=xxxxx;User ID=xxxxxx;Password=xxxxx;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;")
oCon2 = New Data.SqlClient.SqlConnection("Server=xxxxxx,1433;Database=xxxx;User ID=xxxx;Password=xxxxx;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;")
oCon.Open()
oCon2.Open()
oCatCom.Connection = oCon
oCatCom.CommandText = "Select * From myportal_lcat"
oItemCom.Connection = oCon2
oItemCom.CommandText = "Select * From myportal_lhref"
oCatRead = oCatCom.ExecuteReader()
oItemRead = oItemCom.ExecuteReader()
Do While oItemRead.Read
liLinks.Add(New linkItem With {.CatID = oItemRead("catid"), .DName = oItemRead("dname"), .HREF = oItemRead("href")})
Loop
End Sub
Private Class linkItem
Private m_CatID As Integer
Private m_DName As String
Private m_HREF As String
Public Property CatID() As Integer
Get
CatID = m_CatID
End Get
Set(value As Integer)
m_CatID = value
End Set
End Property
Public Property DName() As String
Get
DName = m_DName
End Get
Set(value As String)
m_DName = value
End Set
End Property
Public Property HREF() As String
Get
HREF = m_HREF
End Get
Set(value As String)
m_HREF = value
End Set
End Property
End Class
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
My Portal - Test
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageHeader" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageContent" Runat="Server">
<%Dim t As linkItem %>
<%Do While oCatRead.Read()%>
<section class="links">
<h2><%=oCatRead("name") %></h2>
<ul>
<%For each t In liLinks %>
<%If t.CatID = oCatRead("id") Then %>
<li><a href="<%=t.HREF %>"><%=t.DName %></a></li>
<%End If %>
<%Next %>
</ul>
</section>
<%Loop%>
</asp:Content>
答案 0 :(得分:0)
问题是由于当使用asp.net主页时,首先在主页中调用page_load,然后再在实际页面中调用。但是,两者的代码都运行了两次。
当我在页面加载中将项目添加到列表时初始化声明中的对象列表时,因为page_load运行了两次,所以添加了两次。我将对象列表的初始化移动到page_load而不是声明,这解决了我的问题。