1

我有 ASP.NET 页面、它的代码隐藏和一个类文件:

  • Folder1/page.aspx(asp.net页面),它包含一个label
   <asp:Label runat="server" ID="Label1" Visible="false"></asp:Label>
  • Folder1/page.aspx.vb (code-behind),它像这样调用connection.vb:
    Dim x As New Connection
    Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
    x.checkusernameExists(TextBoxUsername.Text)
    ' I try to access `Boolean variable` Flag from Class file but I can't.
    End Sub
  • App_Code/connection.vb(我创建的类文件)
    Public Class Connection
       Public Sub checkusernameExists(ByVal username1 As String)
       Dim flag as Boolean
       ' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
       End Sub
    End Class


我的问题

1 -我如何Label1从内部ASP.NET page访问Connection.vb

2 -我如何访问Boolean variablefrom Connection.vbinpage.aspx.vb (code behind)

我真的陷入了困境。
谢谢你。

4

3 回答 3

2

使用(公共)属性或方法参数。

您必须问自己以​​下问题:为什么负责连接的类(我假设是数据库)完全可以访问您的 GUI?不要将不同的层相互硬链接,否则您将无法单独使用它们。

我建议让连接类完成它的工作,而不是修改你的前端。相反,控制器(aspx 页面)应该管理它的 GUI 并调用连接类,使用返回值来确定接下来要对Label.

所以返回一个Boolean来表明用户是否有效:

Public Class Connection
   Public Shared Function checkusernameExists(ByVal username1 As String)As Boolean
       Dim userExists As Boolean
       ' acces db to check if the username exists '
       Return userExists 
   End Sub
End Class

在您的页面中:

Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
    Dim userExists As Boolean = Connection.checkusernameExists(TextBoxUsername.Text)
    Label1.Visible = userExists 
    If Label1.Visible Then Label1.Text = "Hello again " & TextBoxUsername.Text
End Sub
于 2013-03-19T10:04:25.770 回答
1

您可以使用函数返回值并将标签作为参数传递。

Public Function SaveChanges(ByRef Label1 As Label, ByVal username1 As String) As Boolean
{
    Return True
}

如果您将标签属性传递给函数而不是传递标签的对象,因为它会耦合两个类,这会更好。

于 2013-03-19T10:00:15.863 回答
1

将标志设为属性并在 checkusernameExists 函数中设置此属性

 Public Class Connection

   Public Property  Flag as Boolean 
   Public Sub checkusernameExists(ByVal username1 As String)

    // set flag here
     Flag = True // or whateever value returned from the database
   ' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
   End Sub
End Class

并在 page.aspx.vb 文件中访问此实例级属性

Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
Label1.Visible= x.Flag;
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
于 2013-03-19T10:05:01.553 回答