Add an asp code into another asp

106 views Asked by At

In jsp and php it's very common to have files with pieces of HTML/Java/PHP code and have other jsp/php files consume them. That's fundamental for reusability.

In asp, M$ created another approach, master pages. But I'm having trouble to get used to it, to be forced to have ALL reusable code in a unique file. In example, some apps with many pages may have a breadcrumb area, while simpler apps won't need it.

Yes I can put those blocks inside a ContentPlaceHolder and just add them empty to asp pages they aren't needed. But I'd rather have them on their own files and include them when needed, instead of "removing" them when not needed.

Another example is about menus. Each app has its own menu. In jsp and PHP I can have a local file with the HTML menu and add it. In asp, the best I could imagine is have the "master master page" with an example menu code, then have a local "nested master page" only with local app's menu, and have asp files consume that "nested master page".

Is it the only way to do these stuff? Or is there a better way for doing it?

1

There are 1 answers

6
John Wu On BEST ANSWER

You have many choices with ASP.NET web forms.

If you just need to share server code, such as utility functions, you can add additional classes to your web project and instantiate/call them just like any other code. Classes added in this manner are accessible to all of your pages.

If you want to share server side code across multiple projects, you can create a new project of type "Class Library," compile it, and set a reference to the resulting DLL from all of your web projects.

If you have a page snippet or section (e.g. a menu system) that is common across pages, you have two choices: custom controls or user controls.

Custom Controls: these are controls written from scratch exclusively using code. Essentially, you write a class which extends Control (directly or indirectly), and you take care of everything. You need to write logic to create child controls that you want to use, and you override the Render method to perform rendering. Typically, you build this control into a redistributable assembly (i.e. a DLL), which can then be used by any ASP.NET applications, simply by placing the assembly in the 'bin' directory of the app (or in the Global Assembly Cache).

User Controls: these control are written using an ascx file, which looks much like an aspx page. i.e. you can simply drag and drop the UI elements that you want to use into the design surface. You don't need to worry about control creation, nor about overriding the Render method.

Sounds to me like you want a user control in this scenario. Here is a helpful walkthrough to get you started.

I will echo scheien's sentiment and tell you that you might want to look carefully at MVC, which is totally different but might fit better with your PHP mindset.