希望有人可以提出一种更好的在网站应用程序页面之间共享Web表单代码的方法。用一个非常基本的示例进行说明,假设我有两个名为“ Page1.aspx”和“ Page2.aspx”的网页,它们的代码分别位于分别名为“ Page1.aspx.vb”和“ Page2.aspx.vb”的页面后面。
两个页面都有一个执行相同操作的简单按钮对象。通常,您只需要在两个页面后面的代码中添加click事件,但是我想做的是将它放置在共享的公共类中一次。
两个页面的HTML
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Page1.aspx.vb" Inherits="Page1" %>
<html>
<head runat="server"></head>
<body>
<form id="Form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Page2.aspx.vb" Inherits="Page2" %>
<html>
<head runat="server"></head>
<body>
<form id="Form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
代码:
Partial Class Page1
Inherits system.web.UI.Page
'I don't want to put the button click event here. How do I reference it from below?
End Class
Partial Class Page2
Inherits system.web.UI.Page
'I don't want to put the button click event here. How do I reference it from below?
End Class
Public Class SharedCode
Inherits system.web.UI.Page
'I want to put the button click event here.
Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click
Response.Write("hello")
End Sub
End Class
请注意,按钮和按钮的代码完全相同。能够将代码保存在一个地方会很高兴,这样您就不必一遍又一遍地重复代码以及分别进行管理。尤其是在页面很多的情况下。
我使用的一种有效的方法是在两个页面共享的页面后面仅使用一个代码:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SharedCode.vb" Inherits="SharedCode" %>
上面,对于“ Page1.aspx”和“ Page2.aspx”,我没有在页面后面使用相同的代码,而是分别使用不同的/特定的“ CodeFile”和“ Inherits”值。然后,对于特定于这些页面的代码,我在每个页面中添加内联<script runat="server">
标签。
同样,此方法有效,但是还有更好的方法吗?