简体   繁体   中英

Accessing a namespace declared in a page code behind from another page ASP.net

I have page say default.aspx in which the code behind file default.aspx.vb contains its partial class and another namespace called mynamesspace. So the default.aspx.vb file is like this

Imports mynamespace

Partial Class Default2
    Inherits System.Web.UI.Page

End Class

Namespace mynamespace
    Public Class status
        Public id, score As Integer
        Public names As String
        Public Function checkscore() As Integer
            Return 1
        End Function
    End Class

End Namespace

But how can I access that same namespace in another page code behind say mypage.aspx? Or is that not permitted?

Absolutely you can do that. Since code behind file is nothing but a class, from your mypage.aspx code behind file you can create an instance of that class and use it:-

Dim cust As New Customer()
Dim result1 As Integer = cust.checkscore()

But I strongly suggest you to create a separate class instead of mixing it with your code behind class.

Or is that not permitted?

As I have already explained this, here is something you can remember about Code behind file as well. Since it is just a class you can have any number of classes in code behind file either in the same namspace or in another namespace (as you have already created). So the question is which class actually acts as code behind class? And the answer is in the Page directive of aspx page:-

<%@ Page Language="VB" AutoEventWireup="true" CodeBehind="Default2.aspx.vb" 
    Inherits="mynamespace.Default2" %>

Here Codebehind attribute informs the aSP.NET framework about the code behind file and Inherits attribute informs about the actual class file associated with aspx page.

I hope this will clear your doubt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM