TOC

This article is currently in the process of being translated into Chinese (~15% done).

The basics:

Events

ASP.NET 是事件驱动的编程方法。PHP和传统的ASP只有一个文件。网页是一行一行的执行。从文件开始执行到文件结束。ASP.NET的执行方法有很大的不同。ASP.NET是事件驱动,事件可以由用户用不同的方法激活。在前面的例子我们用Page_Load方法。实际上Page_Load就是一个事件。 这个方法由Page类在页面装载的时候调用。我们将在下一个例子中用相同的方法。在下个例子中,我们会加几个控件到我们的“hello world” 例子中。为了让事情更有趣, 我们会让用户改变“world”这个词。 看看下面的代码, 我们加了两个控件:“Button”和”Text Box“。

<form id="form1" runat="server">
<div>
    <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    <br /><br />
    <asp:TextBox runat="server" id="TextInput" /> 
    <asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>

你可以看到,在页面上有两个新的控件。但是它们现在还不能做什么事情。如果你想自己试试,可以运行一下看看。如果你点击“button”, 页面只是重新装载。现在,我们用简单的方法让这个“button”做点什么。VS是所见即所得(WYSIWYG)的编辑器。它使创建事件容易很多。

点击VS窗口底部的“Design”按钮。你会看到一个展示页面, 这个页面也是网页运行时的样子。我们想给“button”加个点击事件(click),很容易做,双击“GreetButton", VS 会打开一个页面的CodeBehind文件。你可以看到,代码中已经加入了一个新方法, 名字叫GreetButton_Click。如果你想看看Default.aspx 文件(你需要从Design视窗转到Source视窗),你可以看到”Button“控件加入了一个新属性,这个属性告诉Button, 当用户点击”Button“时调用什么方法。所有这些都是当年双击”button“时, VS自动加入。

现在我们为事件写一些代码。我们希望用TextBox中的内容去替换写有“Hello,world!"Label的文字。很简单,也就是一行代码:

HelloWorldLabel.Text = "Hello, " + TextInput.Text;

Run the project again (ctrl+F5), and you will see the our old page with a couple of new controls. The "Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a name in the textbox, and press the button. Voila, the text is changed, and we have just used our first control event. Notice how we can add code which is not necessarily called unless the user performs a specific task. This is different from the good old Classic ASP/PHP approach, but you will soon get used to it, and you will probably also come to like it a lot!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!