ASP.Net and GetType()
Asked Answered
F

4

6

I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(page.GetType());
}

In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(typeof(Login));
}

it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"?

Thanks in advance!

Footpace answered 14/10, 2008 at 17:26 Comment(0)
G
6

If your code-beside looks like this:

public partial class _Login : BasePage 
 { /* ... */ 
 }

Then you would get the Type object for it with typeof(_Login). To get the type dynamically, you can find it recursively:

Type GetCodeBehindType()
 { return getCodeBehindTypeRecursive(this.GetType());
 }

Type getCodeBehindTypeRecursive(Type t)
 { var baseType = t.BaseType;
   if (baseType == typeof(BasePage)) return t;
   else return getCodeBehindTypeRecursive(baseType);
 }
Geisel answered 14/10, 2008 at 17:35 Comment(0)
F
3

After some additional research I found that if I call Page.GetType().BaseType it returns the code-behind type of the Aspx page.

Footpace answered 14/10, 2008 at 17:53 Comment(0)
K
1

page.GetType().BaseType, it has been said before, but let me elaborate as to why.

Aspx pages inherit from their code-behind pages, meaning that the inheritance hierarchy looks like this:

...
Page
BasePage
Login
ASP_Login

Where the top is the parent and the bottom is the child.

This allows your code behind to be accessible from the aspx page, without requiring all of the generated code related to your actual aspx page to be copied into the base class page.

Kila answered 14/10, 2008 at 18:16 Comment(0)
V
0

It depends where you're calling Display() from. If you're calling it from the ASPX, then you'llse "ASP_login.aspx". If you're calling it from the code-behind (i.e. the Page_Load() method) you should get the Login page type.

Instead of passing the Page in, you might consider just using the Page property (i.e. this.Page.GetType()) which should always be the current page/codebehind type, if I recall correctly.

I should also make the point that you might consider moving this sort of stuff out of the ASPX/codebehind and into some sort of service. It's generally a good idea to minimize the amount of things you do in a code behind and, instead, push logic into a presenter class and follow the MVP pattern for ASP.NET Web Forms development.

Virga answered 14/10, 2008 at 17:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.