ASP.Net and GetType ()

I want to get the type of the "BasePage" object that I am creating. Each page object is based on BasePage. For example, I have Login.aspx and my code and class that has a Display method:

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

In my project structure, I have a default resource file and psuedo-translation resource file. If I installed 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 action "ASP_login.aspx". How can I get the actual code behind the class type to get an object of type Input that comes from BasePage?

Thanks in advance!

+6
reflection c # resourcemanager
source share
4 answers

If your code nearby looks like this:

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

Then you will get a Type object for it using typeof(_Login) . To get a 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); } 
+6
source share

After some further research, I found that if I call Page.GetType (). BaseType returns the Aspx code type.

+3
source share

page.GetType (). BaseType, this was said before, but let me tell you more about why.

Aspx pages inherit from their code pages, which means that the inheritance hierarchy is as follows:

 ... Page BasePage Login ASP_Login 

If the top is parent and the bottom is a child.

This allows your code to be accessible from an aspx page, without having to copy all the generated code associated with your actual aspx page to the base class page.

+1
source share

It depends on where you call Display (). If you call it from ASPX, you will get "ASP_login.aspx". If you call it from code (for example, the Page_Load () method), you should get the type of login page.

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

I also have to say that you might think about porting this kind of thing from ASPX / codebehind and into some kind of service. This is usually a good idea to minimize the amount of things you do in the code behind, and instead move the logic to the presenter class and follow the MVP template for developing ASP.NET web forms.

0
source share

All Articles