asp.net中包含了一种新方法:将商业逻辑代码从表达代码中分离出来。这通常被称为背后的代码,功能非常强大,并且非常容易执行。
实现步骤就是:向asp.net 页面中增加用户界面元素,并为它们指定属性“runat=server”。然后,用.net语言创建一个类文件来操作这些用户界面元素。最后,在asp.net 页面顶部增加一个指令,将用户界面与操作它的类文件附着在一起。
用一个简单的例子就能展示它是如何完成的。下面创建一个名叫webpage.aspx的asp.net页面,在其中粘贴以下代码:
<%@ page language="vb" inherits="dotnet101.mysample.webpage" %>
<html>
<head>
<title>code-behind demo</title>
</head>
<body>
<form id="messageform" runat="server">
<asp:textbox id="message" runat="server" />
<asp:button id="submit" onclick="submit_onclick"
text="send message" runat="server" />
</form>
</body>
</html>
|
请注意增加到“page”指令中的“inherits”属性,它负责通知asp.net页面应该为其商业逻辑使用“dotnet101.mysample.webpage”类。我们已经向这个页面增加了两个asp.net服务器控件,并且为它们和 form控件本身指定了“runat=server”属性。这些都是背后的代码类将要操作的控件。当用户点击“submit”(提交)按钮时,指定给button服务器控件的“onclick”属性就会告诉asp.net引擎激活背后代码类中的submit_onclick事件处理器。
下面,我们需要创建一个背后代码类文件来操作asp.net页面。创建一个名为codebehind.vb的文件,类的visual basic.net 代码如下:
imports system
imports system.web
imports system.web.ui
imports system.web.ui.webcontrols
imports system.web.ui.htmlcontrols
namespace dotnet101.mysample
public class webpage : inherits page
protected messageform as htmlform
protected message as textbox
public sub submit_onclick(sender as object, e as eventargs)
dim output as label = new label
output.text = "you just typed: " & message.text
messageform.controls.add(output)
end sub
end class
end namespace
|
[1] [2] 下一页