0

我创建了一个类,它可以包含一个对象的多个实例,所有的数据都存储在会话中。直到运行时我才知道有多少实例。显示此动态数据的最佳方法是什么。我使用带有代码的 aspx,所以我认为它需要在加载子中发生。

如果它有帮助,继承类,它在 VB 中,但在 c# 中的答案很好:

Imports System.Web.HttpContext

Public Class Student

    Public Property SchoolId As Integer
    Public Property Grade As Integer
    Public Property StudentName As String


    Public Sub AttachToSession(StudentToBeAdded As Student)

        Dim StudentList As New List(Of Student)

        If (Current.Session("student") Is Nothing) Then

            StudentList.Add(StudentToBeAdded)
            Current.Session("student") = StudentList

        Else

            StudentList = Current.Session("student")
            StudentList.Add(StudentToBeAdded)
            Current.Session("student") = StudentList

        End If

    End Sub

End Class
4

2 回答 2

1

您可以使用GridView控件来显示学生信息

标记

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True">
</asp:GridView>

在您的代码中

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

    If Not IsPostBack Then
        GridView1.DataSource = CType(Session("student"), List(Of Student))
        GridView1.DataBind()
    End If

 End Sub
于 2013-01-14T21:08:12.917 回答
0

或者,如果你想要一个自定义的外观和感觉,你可以尝试这样的事情(在你的 aspx 页面中):

<% For Each l_student As Student In CType( Session( "student" ), List(Of Student) ) %>
    <div>
        <p>Name: <%= l_student.StudentName %></p>
        <p>Grade: <%= l_student.Grade %></p>
    </div>
<% Next %>

这将为学生收藏中的每个项目创建一个“div”元素。

请参阅:.NET Framework 中的 ASP.NET 内联表达式简介

不过,您最好在学生班级中创建共享属性:

Public Shared ReadOnly Property Students As List(Of Student)
    Get
        Dim l_studentList As List(Of Student) = TryCast( Current.Session("student"), List(Of Student) )
        If l_studentList Is Nothing Then
            l_studentList = New List(Of Student)
            Current.Session("student") = l_studentList
        End If

        Return l_studentList
    End Get
End Property

那么你的 aspx 将是:

<% For Each l_student As Student In Student.Students %>
...
于 2013-01-14T21:16:39.970 回答