Question

I know it is possible to use a class in the App_Code folder from my Web-Form Class. But, Is posible to call my Web-Form class from a class that is inside App_Code?

How?

thanks

Was it helpful?

Solution

Remember: when working on the web, everything happens in the context a request/response. What you want to do is provide that context to any method in your App_Code that needs to see your webform. Those methods will need an additional HttpContext parameter, like this:

public void AppCodeMethod(HttpContext currentContext)

That will give you access to the context's Request and Response properties. You could also have those methods accept an instance of a webform class, but generally when I've seen this it's been a sign of a weak understanding how webforms work, and a much better solution was found after abandoning that approach.

The one thing you should not do is have a class in App_Code that relies on persistant state. Those classes should have no fields or properties that you expect to hold a value across individual events firing. In ASP.Net, the entire thread housing your class is reset between each event that you handle. This is important to understand: every time you handle an event, a brand new instance of your form class is created, your page_load method runs again, the event code finally runs, and then the form class (and the whole thread) is destroyed (or reset to be ready to handle a request from a completely different user). Web Forms tries to create an abstraction to make the http layer appear like a single, persistent page, but this abstraction leaks all over the place.

Therefore, the best use of App_Code classes is generally to reserve them for utility methods that are shared by multiple pages, but still only depend on information from a single http request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top