So, instead of defining HTML controls in your pages directly, you define an ASP.NET Server
Control with the following syntax, where the italicized parts differ for each control.
<asp:TypeOfControl ID=”ControlName“ Runat=”Server” />
For the controls that ship with ASP.NET 4 you always use the asp: prefix followed by the name of
the control. For example, to create a TextBox that can hold the same welcome message and current
time, you can use the following syntax:
<asp:TextBox ID=”Message” Runat=”Server” />
Note that the control has two attributes: ID and Runat. The ID attribute is used to uniquely identify
a control on the page, so you can program against it. It’s important that each control on the page
has a unique ID; otherwise the ASP.NET runtime won’t understand what control you’re referring to.
If you accidentally type a duplicate control ID, VWD will signal the problem in the error list. The
mandatory Runat attribute is used to indicate that this is a control that lives on the server. Without
this attribute, the controls won’t be processed and will end up directly in the HTML source. If you
ever feel you’re missing a control in the final output in the HTML of the browser, ensure that the
control has this required attribute. Note that for non-server elements, like plain HTML elements,
the Runat attribute is optional. With this attribute on non-server controls, they can be reached by
your programming code. You learn more about this later in the book.
You can easily add the Runat attribute to an existing element by typing runat and pressing the
Tab key.
The preceding example of the TextBox is using a self-closing tag where the closing slash (/) is embedded
in the opening tag. This is quite common for controls that don’t need to contain child content
such as text or other controls. However, the long version, using a separate closing tag is acceptable as
well:
<asp:TextBox ID=”Message” Runat=”Server”></asp:TextBox>
You can control the default behavior of closing tags per tag using Tools ➪ Options ➪ Text Editor ➪
HTML ➪ Formatting ➪ Tag Specific Options.
You can program against this text box from code that is either placed inline with the page or in a
separate Code Behind file, as you saw in Chapter 2. To set the welcome message and the time, you
can use the following code:
VB.NET
Message.Text = “Hello World, the time is “ & DateTime.Now.TimeOfDay.ToString()
C#
Message.Text = “Hello World, the time is “ + DateTime.Now.TimeOfDay.ToString();
The definition of the control in the markup section of the page is now separated from the actual
code that defines the text displayed in the text box, making it easier to define and program the text
box (or any other control) because it enables you to focus on one task at a time: either declaring the
control and its visual appearance in the markup section of the page, or programming its behavior
from a code block.
No hay comentarios:
Publicar un comentario