将一个 asp 代码添加到另一个 asp

Add an asp code into another asp

在 jsp 和 php 中,文件包含 HTML/Java/PHP 代码段并让其他 jsp/php 文件使用它们是很常见的。这是可重用性的基础。

在asp中,M$创造了另一种方法,master pages。但是我很难习惯它,被迫将所有可重用代码放在一个唯一的文件中。例如,一些页面很多的应用程序可能有一个面包屑区域,而更简单的应用程序则不需要它。

是的,我可以将这些块放在 ContentPlaceHolder 中,然后将它们空添加到 asp 不需要的页面。但我宁愿将它们放在自己的文件中并在需要时包含它们,而不是在不需要时 "removing" 它们。

另一个例子是关于菜单的。每个应用程序都有自己的菜单。在 jsp 和 PHP 中,我可以使用 HTML 菜单创建一个本地文件并添加它。在 asp 中,我能想到的最好的办法是让 "master master page" 带有示例菜单代码,然后让本地 "nested master page" 仅带有本地应用程序的菜单,并让 asp 文件消耗"nested master page".

这是做这些事情的唯一方法吗?或者有更好的方法吗?

您可以使用 ASP.NET 网络表单进行多种选择。

如果您只需要共享服务器代码,例如实用程序函数,您可以向您的 Web 项目添加额外的 类,然后像添加任何其他代码一样 instantiate/call 它们。 Class您的所有页面都可以访问以这种方式添加的内容。

如果你想在多个项目之间共享服务器端代码,你可以创建一个“Class 库”类型的新项目,编译它,并设置对所有 Web 生成的 DLL 的引用项目。

如果您有跨页面通用的页面片段或部分(例如菜单系统),则您有 two choices:自定义控件或用户控件。

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.

在我看来,您想要在这种情况下进行用户控制。这是一个有用的 walkthrough 帮助您入门。

我会回应 scheien 的观点,并告诉您您可能需要仔细研究 MVC,它完全不同,但可能更适合您的 PHP 心态。