Tải bản đầy đủ - 0 (trang)
Chapter 14: Applications with ASP.NET, MVC, JavaScript, and HTML

Chapter 14: Applications with ASP.NET, MVC, JavaScript, and HTML

Tải bản đầy đủ - 0trang




today’s consumer. However the addition of these technologies presents a bit of problem: you need to

understand each well enough to decide if and when you should use them.

The goal of this chapter is to introduce you to different frameworks and technologies available

within ASP.NET and Visual Studio and to provide you with enough information to enable you to

decide which you’d like to explore further.


Visual Studio 2012 offers a wide range of features to assist you in building applications: IntelliSense,

code snippets, integrated debugging, CSS style support, and the ability to target multiple versions

of the .NET framework are a few examples. When working with ASP.NET you’ll see that many of

these productivity features also apply when working with inline code, client-side JavaScript code,

XML, and HTML markup.

Web Site and Web Application Projects

Visual Studio gives you two models for ASP.NET projects:



Web site projects

Web application projects

The Web application project model is very similar to other project types. The structure is based on

a project file (.vbproj), and all VB code in the project compiles into a single assembly. To deploy

it you copy the assembly along with markup and static content files to the server. You can create

a new Web application project by selecting File Í New Í Project from the main menu in Visual


The Website project model was added with Visual Studio 2005. This model is designed to be very

lightweight and familiar to Web developers and designers coming to Visual Studio from other

tools. It uses a folder structure to defi ne the contents of a project, enabling you to open a website

just by pointing Visual Studio at a folder or a virtual directory. The default deployment model uses

dynamic compilation whereby VB source fi les are deployed along with markup and other content

fi les. Alternately, the project can be precompiled, which creates an assembly per folder or an assembly per page, depending on the settings passed to the compiler. You can create a new website by

selecting File Í New Í Web Site from the main menu in Visual Studio.

Web Server Options

ASP.NET gives you three options to host your Web projects:




ASP.NET Development Server

IIS Express



c14.indd 562

12/7/2012 3:41:25 PM

Server-Side Development

x 563

IIS Express is the default for Web application projects, and the ASP.NET Development Server is the

default for Website projects. IIS Express and the ASP.NET Development Server are lightweight and

convenient but both only allow you to run and test pages locally.

The mechanism used to select which server will be used depends on the project type. For Website

projects, you can choose in the New Web Site dialog by selecting an option from the Web Location

drop-down. Selecting File System will use the development server, while selecting HTTP will use IIS.

For Web application projects, you can select which server to use after the project has been created.

This is done through the Web tab of the project properties. You can even switch back and forth,

enabling you to do most of your development with the IIS Express but switching to IIS when you

want to test in an environment closer to production.


ASP.NET offers three main server-side development models for building Web applications:




Web Forms

ASP.NET MVC (or just MVC for short)

Web Pages

Web Forms was the original Web development model in .NET and is now in version 4.5. MVC was

fi rst released in March 2009 and is now in version 4. Web Pages (and the associated Razor view

engine) was fi rst released in January 2011 and is now in version 2.

Web Forms

The goal of Web Forms is to make the Web development experience as close to the Windows Forms

(or Classic VB) development experience as possible. You build pages by dragging and dropping controls on a design surface, you set properties of those controls though the Properties window, and

you add event handlers by double-clicking the controls. This gives separation between the code generated by the designer and the code you write.

Following the premise that the most effective way to learn a new technology is to use it, you’ll now

walk through a sample application of the core features of Web Forms. You can follow along with the

instructions below or you can examine the project included with the code downloads for the book.

Open Visual Studio and select File Í New Í Project. In the New Project dialog, select the ASP.NET

Web Forms Application template, set the Name to WebFormsDemo, and click the OK button (see

Figure 14-1).

The project created by the template is a working Web application containing several sample pages.

The project is designed to be a starting point you can use for your custom applications, and that

is exactly how you will use it. Run the application by pressing the F5 key to see how it looks (see

Figure 14-2).


c14.indd 563

12/7/2012 3:41:25 PM




FIGURE 14-1: New Web Forms project

FIGURE 14-2: Default page of sample site generated by the project template


c14.indd 564

12/7/2012 3:41:25 PM

Server-Side Development

x 565


Web Forms applications are made up of one or more pages. Pages are also known as Web Forms

because they are designed to emulate a form in a Windows Forms application. Pages consist of a

combination of markup and code. The code can use the classic ASP style and be placed inline in the

same fi le as your markup, but the more common approach is to use a code-behind file. The idea of

using the code-behind model is to separate the business logic and presentation into their own files.

This makes it easier to work with your pages, especially if you are working in a team environment

where visual designers work on the UI of the page and coders work on the business logic that sits

behind the presentation pieces.

Add a page to the sample project by right-clicking on the project and select Add Í New Item. In

the Add New Item dialog, select the Web Form template, set the Name to ServerControls.aspx, and

click the Add button (see Figure 14-3).

FIGURE 14-3: Adding a Web Form to the project

A new item will be added in the Solution Explorer to represent your page, but three files were actually created: ServerControls.aspx, which contains the markup; ServerControls.aspx.designer.vb,

which contains code generated by Visual Studio as you work with the markup (you will very rarely

have to look at or edit this file); and ServerControls.aspx.vb, which contains the VB code-behind for

the page.

To see the code-behind, right-click on ServerControls.aspx in the Solution Explorer and select View

Code. At the top of the file you will fi nd the declaration of the ServerControls class. Note that this

class inherits from System.Web.UI.Page, which is the base class for pages in Web Forms (see

Figure 14-4).


c14.indd 565

12/7/2012 3:41:25 PM




FIGURE 14-4: Code-behind for the ServerControls page

Now switch back to the markup. If the fi le is not already open, you can open it by right-clicking on

ServerControls.aspx in the Solution Explorer and selecting View Markup. At the top of the markup

you will fi nd a <% Page %> directive. It is the CodeBehind and Inherits attributes of this directive

that link the markup fi le with the code-behind fi le. In this fi le you will also fi nd the Form control

which will contain the other controls you place on the page (see Figure 14-5).

FIGURE 14-5: Markup for the ServerControls page


c14.indd 566

12/7/2012 3:41:26 PM

Server-Side Development

x 567

Server Controls

Server controls are logical elements that represent user interface and behavior when rendered on a

page. You add the control to the page and configure its properties, and ASP.NET determines the

appropriate HTML tags (and quite often JavaScript) to send to the browser to implement desired

functionality. The control can be something simple like a button, or something complex like a grid

that supports sorting and fi ltering.

To use drag-and-drop to add controls to your page, click the Design or Split tab at the bottom of the

design area in the IDE. When either of these views is active, you can drag and drop controls from

the Toolbox onto the design surface, or you can place the cursor in the location where you want the

control to appear and then double-click the control.

You also can work directly in the markup. Because many developers prefer this, it is the default

view of a page. Hand-coding your pages may seem to be a slower approach than simply dragging

and dropping controls onto a design surface, but it isn’t as slow as you might think. Many of the

same productivity features available when editing Visual Basic code, such as IntelliSense and Code

Snippets, are also available when editing page markup. Also, like Design view, the Source view

enables you to drag and drop controls from the Toolbox into the markup itself.

Whether you are in Design view or Source view, you can highlight a control to edit its properties in

the Properties window. Changing the properties will change the appearance or behavior of the highlighted control. Because all controls inherit from a specific base class (WebControl), you can highlight multiple controls at the same time and change the base properties of all the controls at once by

holding down the Ctrl key as you make your control selections.

On the ServerControls.aspx page you want to add a DropDownList and set the ID to

FruitDropDown; add a Button and set the ID to SubmitButton and Text to Submit; and add

a Label and set the ID to ResultLabel. Also set the title of the page by setting the value of the

element in the markup to Server Control Example.<br /><br />Use the techniques described in this section to add these controls and set their properties so that the<br /><br />page looks like Figure 14-6.<br /><br />If you chose to add the markup using the code editor instead of the designer, the contents of the<br /><br />page should look something like this (code fi le: ServerControls-Step01.aspx):<br /><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><br /><head runat="server"><br /><br /><title>Server Control Example


c14.indd 567

12/7/2012 3:41:26 PM




At this point you could view the page by selecting ServerControls.aspx in the Solution Explorer and

pressing F5, but there won’t be any data or behavior. You’ll add those next using page and control


FIGURE 14-6: Split view of ServerControls.aspx with controls added

Page Events

You will often want to handle the events raised as the page is being generated. This enables you to

tailor the generation of the page to suit your needs.

Here is a list of the commonly used events in the page life cycle. Additional events are possible, but

those are primarily used by developers creating custom server controls.




c14.indd 568

12/7/2012 3:41:26 PM

Server-Side Development








x 569

Of these, the most frequently used is the Load event, which is generally used to initialize the

properties of the page and its child controls. You’ll use the Load event to add some data into the


Right-click on the ServerControls.aspx fi le and select View Code to open the Code view of the

page. Notice that the shell for the method that handles the Load event (Page_Load) is already there.

Inside this method, write the code to populate the choices in the drop-down by adding the names

of a few of your favorite fruits into the Items collection of the FruitDropDown control. Also, the

ResultLabel shouldn’t show any text when the page is fi rst loaded, so set its Text property to an

empty string (code fi le: ServerControls-Step02.aspx.vb).

Protected Sub Page_Load(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Me.Load





ResultLabel.Text = String.Empty

End Sub

Next, you need to add the code to handle the event raised when the SubmitButton is clicked.

Control Events

ASP.NET Web Forms uses an event-driven model similar to that used with Windows Forms. The

key difference between ASP.NET Web Forms events and those of Windows Forms is what happens when an event occurs. The objects that make up a Windows Form exist as long as the form

exists; thus, they maintain state across user interactions. Because of the stateless model of the Web,

the objects that make up the page (in the sample project that means the page, the drop-down, the

button, and the label) only live long enough to generate the markup for that page. Once a request

is complete and the fi nal markup has been sent to the client browser, the objects that comprise the

page are orphaned, and they await garbage collection.

Since the original objects are no longer available, new objects will need to be created for the event

code to run. Therefore, when a user interaction triggers a server-side event, a request is sent to the

server that includes information about the event; the page and the control objects are created on the

server; the internal state of these objects is set using information passed in the request; the event


c14.indd 569

12/7/2012 3:41:27 PM




handler executes; and an updated version of the page is sent

back to the client browser. This process is called a postback.

How do you hook up these events for server controls? Again,

the model is similar to that seen in Windows Forms. You can

double-click a control in the Design view to add the handler

for the default event for that control, you can use Event view

in the Properties window (see Figure 14-7), or you can use the

drop-downs at the top of the Code Editor (see Figure 14-8).

Add the event handler for the Click event of the

SubmitButton. In the event handler, show the value the user

selected from the FruitDropDown in the ResultLabel (code

fi le: ServerControls-Step02.aspx.vb).

FIGURE 14-7: Adding an event handler

using the Properties window

Private Sub SubmitButton_Click(sender As Object, e As EventArgs) _

Handles SubmitButton.Click

ResultLabel.Text = "You selected: " & FruitDropDown.Text

End Sub

FIGURE 14-8: Adding an event handler using the drop-downs in the code editor

Figure 14-9 shows the page after a fruit has been selected and the

Submit button has been clicked.

The sample application seems to work correctly, but if you inspect

the items in the FruitDropDown after clicking the SubmitButton at

least once, you’ll notice that the options appear multiple times (see

Figure 14-10).

It seems that the values in the control are being persisted across

page requests, and that the code in the Page_Load event handler is



You selected: Orange

FIGURE 14-9: Running page

after the Submit button has been



c14.indd 570

12/7/2012 3:41:27 PM

Server-Side Development

x 571

adding to the existing items instead of populating the Items collection from scratch. It turns out that

this is exactly what is happening through a mechanism known as ViewState.


As previously mentioned, the Page object and each of its child

controls are constructed on each request. The ASP.NET team

needed a way to persist some of the properties of the controls across

postbacks to maintain the illusion that pages were living across

requests. What they came up with is a somewhat ingenious trick

called ViewState.

The properties that need to be persisted across calls are packaged up and encoded and then placed in a hidden field within the

page. When a postback occurs, these values are unpackaged and

placed into the properties of the newly created server controls. The

ViewState for a page will look something like this:

FIGURE 14-10: Contents of the

drop-down after the Submit button has been pressed twice




JtYR8JfiZ/9yASSM5EIp" />

ViewState can be turned off at the page or the control level via the EnableViewState property. The

ASP.NET team has gone to great lengths to keep the size of ViewState as small as possible but it still

needs to be monitored and managed. Unchecked, ViewState can get large enough to affect the load

times of your pages.

With these facts in mind, a simple adjustment is all that is required to address the issue with the sample project. In the Page_Load event handler, you need to check if the current request is a postback.

If it is, the items will be populated automatically from the ViewState; otherwise, you need to execute

your code as follows to get the items into the control (code file: ServerControls-Step03.aspx.vb):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _

Handles Me.Load

If Not IsPostBack Then





ResultLabel.Text = String.Empty

End If

End Sub

Now, no matter how many times you click the button, the list will have the proper number of items.

Master and Content Pages

Many Web applications are built so that each page of the application has a similar look and feel;

and there may be common page elements such as a header, navigation sections, advertisements,


c14.indd 571

12/7/2012 3:41:27 PM




footers, and more. Most people prefer uniformity in their applications in order to give end users a

consistent experience across pages.

Web Forms includes a feature called master pages that enable you to create a template (or a set of

templates) that defi ne the common elements for a set of pages. Once a master page is created, you

can then create a content page that defi nes the content specific to a single page. The content page

and the master page are associated by attributes in the Page directive so ASP.NET can combine the

two fi les into a single web page to display in a browser (see Figure 14-11).

Master Page


Content Page





Combined Page


FIGURE 14-11: Relationship between master and content pages

A master page contains one or more ContentPlaceHolder controls that will be “filled in” by the

associated content pages. The master page included in your project (Site.Master) contains three of

these placeholders (see Figure 14-12).

You’ll create a content page using this master page. Right-click on the project in the Solution

Explorer and select Add Í New Item. In the Add New Item dialog select the Web Form using

Master Page template, setting the Name to Products.aspx, and click the Add button (see

Figure 14-13).

You will then be presented with the Select a Master Page dialog. Your project has only one master

page (Site.Master); select it and click the OK button (see Figure 14-14).


c14.indd 572

12/7/2012 3:41:27 PM

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 14: Applications with ASP.NET, MVC, JavaScript, and HTML

Tải bản đầy đủ ngay(0 tr)