20486C ENU TrainerHandbook
20486C ENU TrainerHandbook
20486C
Developing ASP.NET MVC 5 Web
Applications
MCT USE ONLY. STUDENT USE PROHIBITED
ii Developing ASP.NET MVC 5 Web Applications
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
Released: 01/2018
MCT USE ONLY. STUDENT USE PROHIBITED
MICROSOFT LICENSE TERMS
MICROSOFT INSTRUCTOR-LED COURSEWARE
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its
affiliates) and you. Please read them. They apply to your use of the content accompanying this agreement which
includes the media on which you received it, if any. These license terms also apply to Trainer Content and any
updates and supplements for the Licensed Content unless other terms accompany those items. If so, those terms
apply.
BY ACCESSING, DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS.
IF YOU DO NOT ACCEPT THEM, DO NOT ACCESS, DOWNLOAD OR USE THE LICENSED CONTENT.
If you comply with these license terms, you have the rights below for each license you acquire.
1. DEFINITIONS.
a. “Authorized Learning Center” means a Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, or such other entity as Microsoft may designate from time to time.
b. “Authorized Training Session” means the instructor-led training class using Microsoft Instructor-Led
Courseware conducted by a Trainer at or through an Authorized Learning Center.
c. “Classroom Device” means one (1) dedicated, secure computer that an Authorized Learning Center owns
or controls that is located at an Authorized Learning Center’s training facilities that meets or exceeds the
hardware level specified for the particular Microsoft Instructor-Led Courseware.
d. “End User” means an individual who is (i) duly enrolled in and attending an Authorized Training Session
or Private Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.
e. “Licensed Content” means the content accompanying this agreement which may include the Microsoft
Instructor-Led Courseware or Trainer Content.
f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, and (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program.
g. “Microsoft Instructor-Led Courseware” means the Microsoft-branded instructor-led training course that
educates IT professionals and developers on Microsoft technologies. A Microsoft Instructor-Led
Courseware title may be branded as MOC, Microsoft Dynamics or Microsoft Business Group courseware.
h. “Microsoft IT Academy Program Member” means an active member of the Microsoft IT Academy
Program.
i. “Microsoft Learning Competency Member” means an active member of the Microsoft Partner Network
program in good standing that currently holds the Learning Competency status.
j. “MOC” means the “Official Microsoft Learning Product” instructor-led courseware known as Microsoft
Official Course that educates IT professionals and developers on Microsoft technologies.
k. “MPN Member” means an active Microsoft Partner Network program member in good standing.
MCT USE ONLY. STUDENT USE PROHIBITED
l. “Personal Device” means one (1) personal computer, device, workstation or other digital electronic device
that you personally own or control that meets or exceeds the hardware level specified for the particular
Microsoft Instructor-Led Courseware.
m. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective using Microsoft Instructor-Led Courseware.
These classes are not advertised or promoted to the general public and class attendance is restricted to
individuals employed by or contracted by the corporate customer.
n. “Trainer” means (i) an academically accredited educator engaged by a Microsoft IT Academy Program
Member to teach an Authorized Training Session, and/or (ii) a MCT.
o. “Trainer Content” means the trainer version of the Microsoft Instructor-Led Courseware and additional
supplemental content designated solely for Trainers’ use to teach a training session using the Microsoft
Instructor-Led Courseware. Trainer Content may include Microsoft PowerPoint presentations, trainer
preparation guide, train the trainer materials, Microsoft One Note packs, classroom setup guide and Pre-
release course feedback form. To clarify, Trainer Content does not include any software, virtual hard
disks or virtual machines.
2. USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is licensed on a one copy
per user basis, such that you must acquire a license for each individual that accesses or uses the Licensed
Content.
2.1 Below are five separate sets of use rights. Only one set of rights apply to you.
2.2 Separation of Components. The Licensed Content is licensed as a single unit and you may not
separate their components and install them on different devices.
2.3 Redistribution of Licensed Content. Except as expressly provided in the use rights above, you may
not distribute any Licensed Content or any portion thereof (including any permitted modifications) to any
third parties without the express written permission of Microsoft.
2.4 Third Party Notices. The Licensed Content may include third party code tent that Microsoft, not the
third party, licenses to you under this agreement. Notices, if any, for the third party code ntent are included
for your information only.
2.5 Additional Terms. Some Licensed Content may contain components with additional terms,
conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to your use of that respective component and supplements the terms described in this agreement.
a. Pre-Release Licensed Content. This Licensed Content subject matter is on the Pre-release version of
the Microsoft technology. The technology may not work the way a final version of the technology will
and we may change the technology for the final version. We also may not release a final version.
Licensed Content based on the final version of the technology may not contain the same information as
the Licensed Content based on the Pre-release version. Microsoft is under no obligation to provide you
with any further content, including any Licensed Content based on the final version of the technology.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or
through its third party designee, you give to Microsoft without charge, the right to use, share and
commercialize your feedback in any way and for any purpose. You also give to third parties, without
charge, any patent rights needed for their products, technologies and services to use or interface with
any specific parts of a Microsoft technology, Microsoft product, or service that includes the feedback.
You will not give feedback that is subject to a license that requires Microsoft to license its technology,
technologies, or products to third parties because we include your feedback in them. These rights
survive this agreement.
c. Pre-release Term. If you are an Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, MPN Member or Trainer, you will cease using all copies of the Licensed Content on
the Pre-release technology upon (i) the date which Microsoft informs you is the end date for using the
Licensed Content on the Pre-release technology, or (ii) sixty (60) days after the commercial release of the
technology that is the subject of the Licensed Content, whichever is earliest (“Pre-release term”).
Upon expiration or termination of the Pre-release term, you will irretrievably delete and destroy all copies
of the Licensed Content in your possession or under your control.
MCT USE ONLY. STUDENT USE PROHIBITED
4. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more
rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only
allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
• access or allow any individual to access the Licensed Content if they have not acquired a valid license
for the Licensed Content,
• alter, remove or obscure any copyright or other protective notices (including watermarks), branding
or identifications contained in the Licensed Content,
• modify or create a derivative work of any Licensed Content,
• publicly display, or make the Licensed Content available for others to access or use,
• copy, print, install, sell, publish, transmit, lend, adapt, reuse, link to or post, make available or
distribute the Licensed Content to any third party,
• work around any technical limitations in the Licensed Content, or
• reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this
limitation.
5. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to
you in this agreement. The Licensed Content is protected by copyright and other intellectual property laws
and treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the
Licensed Content.
6. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations.
You must comply with all domestic and international export laws and regulations that apply to the Licensed
Content. These laws include restrictions on destinations, end users and end use. For additional information,
see www.microsoft.com/exporting.
7. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.
8. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon termination of this agreement for any
reason, you will immediately stop all use of and delete and destroy all copies of the Licensed Content in
your possession or under your control.
9. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed
Content. The third party sites are not under the control of Microsoft, and Microsoft is not responsible for
the contents of any third party sites, any links contained in third party sites, or any changes or updates to
third party sites. Microsoft is not responsible for webcasting or any other form of transmission received
from any third party sites. Microsoft is providing these links to third party sites to you only as a
convenience, and the inclusion of any link does not imply an endorsement by Microsoft of the third party
site.
10. ENTIRE AGREEMENT. This agreement, and any additional terms for the Trainer Content, updates and
supplements are the entire agreement for the Licensed Content, updates and supplements.
12. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws
of your country. You may also have rights with respect to the party from whom you acquired the Licensed
Content. This agreement does not change your rights under the laws of your country if the laws of your
country do not permit it to do so.
13. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS" AND "AS
AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT AND ITS RESPECTIVE
AFFILIATES GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. YOU MAY
HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT
CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT AND
ITS RESPECTIVE AFFILIATES EXCLUDES ANY IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
14. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT, ITS RESPECTIVE AFFILIATES AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP
TO US$5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL,
LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this
agreement are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre
pays si celles-ci ne le permettent pas.
Acknowledgments
Microsoft Learning wants to acknowledge and thank the following for their contribution toward
developing this title. Their effort at various stages in the development has ensured that you have a good
classroom experience.
Ishai Ram – Lead Content Developer
Ishai is the Vice President of SELA Group. He has over 20 years of experience as a professional trainer and
consultant on computer software and electronics.
Contents
Module 1: Exploring ASP.NET MVC 5
Module Overview 01-1
Lesson 1: Overview of Microsoft Web Technologies 01-2
Lesson 2: Overview of ASP.NET 01-10
Lesson 3: Introduction to ASP.NET MVC 5 01-18
Lab: Exploring ASP.NET MVC 5 01-21
Module Review and Takeaways 01-23
Module 10: Using JavaScript and jQuery for Responsive MVC 5 Web Applications
Module Overview 10-1
Lesson 1: Rendering and Executing JavaScript Code 10-2
Lesson 2: Using jQuery and jQueryUI 10-8
Lab: Using JavaScript and jQuery for Responsive MVC 5 Web Applications 10-15
Module Review and Takeaways 10-17
MCT USE ONLY. STUDENT USE PROHIBITED
xv Developing ASP.NET MVC 5 Web Applications
Course Description
This third release (‘C’) MOC version of course 20486C has been developed on GA software.
Microsoft Learning has released the ‘C’ version with enhanced PowerPoint slides, copy-edited
content, and Course Companion content on Microsoft Learning site.
In this 5-day course, the professional web developers will learn to develop advanced ASP.NET
MVC application using .NET Framework 4.6 tools and technologies. The focus will be on coding
activities that enhance the performance and scalability of the Web site application. This course
will also prepare the student for exam 70-486.
Audience
This course is intended for professional web developers who use Microsoft Visual Studio in an individual-
based or team-based, small-sized to large development environment. Candidates for this course are
interested in developing advanced web applications and want to manage the rendered HTML
comprehensively. They want to create websites that separate the user interface, data access, and
application logic.
Student Prerequisites
This course requires that you meet the following prerequisites:
Students who attend this training can meet the prerequisites by attending the following courses or by
obtaining equivalent knowledge and skills:
• 20483B Programming in C#
Course Objectives
• Describe the Microsoft Web Technologies stack and select an appropriate technology to use to
develop any given application.
• Design the architecture and implementation of a web application that will meet a set of functional
requirements, user interface requirements, and address business models.
MCT USE ONLY. STUDENT USE PROHIBITED
ii About This Course
• Create MVC Models and write code that implements business logic within Model methods,
properties, and events.
• Add Controllers to an MVC Application to manage user interaction, update models, and select and
return Views.
• Create Views in an MVC application that display and edit data and interact with Models and
Controllers.
• Run unit tests and debugging tools against a web application in Visual Studio 2017.
• Develop a web application that uses the ASP.NET routing engine to present friendly URLs and a
logical navigation hierarchy to users.
• Implement a consistent look and feel, including corporate branding, across an entire MVC web
application.
• Use partial page updates and caching to reduce the network bandwidth used by an application and
accelerate responses to user requests.
• Write JavaScript code that runs on the client-side and utilizes the jQuery script library to optimize the
responsiveness of an MVC web application.
• Implement a complete membership system in an MVC 5 web application.
• Build an MVC application that resists malicious attacks and persists information about users and
preferences.
• Describe how to write a Windows Azure web service and call it from and MVC application.
• Describe what a Web API is and why developers might add a Web API to an application.
• Modify the way browser requests are handled by an MVC application.
• Describe how to package and deploy an ASP.NET MVC 5 web application from a development
computer to a web server for staging or production.
Course Outline
The course outline is as follows:
Module 1, “Exploring ASP.NET MVC 5", provides an overview of the Microsoft web technologies stack.
It also describes the three programming models available in ASP.NET 4.5 such as web pages, web
forms, and MVC.
Module 2, “Designing ASP.NET MVC 5 Web Applications", explains the planning of the overall
architecture, controllers, views, and models of the MVC 5 web application.
Module 3, “Developing ASP.NET MVC 5 Models", explains how to create Models in an MVC 5 web
application. The module also describes how to implement a connection to a database using the Entity
Framework.
Module 4, “Developing ASP.NET MVC 5 Controllers", explains how to create Controllers in an MVC 5
web application. The module also describes how to write code in action filters that executes before or
after a controller action.
Module 5, “Developing ASP.NET MVC 5 Views", explains how to create Views in an MVC 5 application
that display and edit data and interact with Models and Controllers.
Module 6, “Testing and Debugging ASP.NET MVC 5 Web Applications", explains how to unit test the
components of an MVC 5 application and to implement exception handling strategy for the
application.
Module 7, “Structuring ASP.NET MVC 5 Web Applications", explains how to structure an MVC 5 web
application that uses routing engine and navigation controls.
Module 8, “Applying Styles to ASP.NET MVC 5 Web Applications", explains how to implement a
consistent look and feel to an MVC application by using a template view.
MCT USE ONLY. STUDENT USE PROHIBITED
About This Course iii
Module 9, “Building Responsive Pages in ASP.NET MVC 5 Web Applications" explains how to use
partial page updates and caching to build responsive pages in an MVC 5 web application.
Module 10, “Using JavaScript and jQuery for Responsive MVC 5 Web Applications", explains how to
increase the responsiveness of the MVC 5 web application by using JavaScript and jQuery.
Module 11, “Controlling Access to ASP.NET MVC 5 Web Applications", explains how to implement
authentication and authorization for accessing the MVC 5 web application.
Module 12, “Building a Resilient ASP.NET MVC 5 Web Application", explains how to build an MVC 5
web application that is stable, reliable, resists malicious attacks, and persists information about users
and preferences.
Module 13, “Implementing Web APIs in ASP.NET MVC 5 Web Applications”, provides an overview of
Web API and explains how to develop a Web API and call it from other applications.
Module 14, “Handling Requests in ASP.NET MVC 5 Web Applications", describes how to create HTTP
Modules and HTTP Handlers to handle requests in an MVC 5 web application. The module also
describes the use of Web Sockets in creating a live data feed in the MVC 5 web application.
Module 15, “Deploying ASP.NET MVC 5 Web Applications", explains how to deploy a completed MVC
application to a web server or Windows Azure.
MCT USE ONLY. STUDENT USE PROHIBITED
iv About This Course
Course Materials
The following materials are included with your kit:
• Course Handbook: a succinct classroom learning guide that provides the critical technical
information in a crisp, tightly-focused format, which is essential for an effective in-class learning
experience.
• Lessons: guide you through the learning objectives and provide the key points that are critical to
the success of the in-class learning experience.
• Labs: provide a real-world, hands-on platform for you to apply the knowledge and skills learned
in the module.
• Module Reviews and Takeaways: provide on-the-job reference material to boost knowledge
and skills retention.
• Modules: include companion content, such as questions and answers, detailed demo steps and
additional reading links, for each lesson. Additionally, they include Lab Review questions and
answers and Module Reviews and Takeaways sections, which contain the review questions and
answers, best practices, common issues and troubleshooting tips with answers, and real-world
issues and scenarios with answers.
• Resources: include well-categorized additional resources that give you immediate access to the
most current premium content on TechNet, MSDN®, or Microsoft® Press®.
• Course evaluation: At the end of the course, you will have the opportunity to complete an online
evaluation to provide feedback on the course, training facility, and instructor.
• To provide additional comments or feedback on the course, send an email to
[email protected]. To inquire about the Microsoft Certification Program, send an
email to [email protected].
MCT USE ONLY. STUDENT USE PROHIBITED
About This Course v
Module 1
Exploring ASP.NET MVC 5
Contents:
Module Overview 01-1
Module Overview
Microsoft ASP.NET MVC 5 and the other web technologies of the .NET Framework help you create and
host dynamic, powerful, and extensible web applications. ASP.NET MVC 5 supports agile, test-driven
development and the latest web standards such as HTML 5. To build robust web applications, you need to
be familiar with the technologies and products in the Microsoft web stack. You also need to know how
ASP.NET applications work with IIS, Visual Studio, SQL Server, Microsoft Azure, and Microsoft Azure SQL
Database to deliver engaging webpages to site visitors. To choose a programming language that best
suits a set of business requirements, you need to know how Model-View-Controller (MVC) applications
differ from the other ASP.NET programming models: Web Pages and Web Forms.
The web application that you will design and develop in the labs throughout this course will help you
develop web applications that fulfill business needs.
Objectives
After completing this module, you will be able to:
• Describe the role of ASP.NET in the web technologies stack, and how to use ASP.NET to build web
applications.
• Describe the three programming models available in ASP.NET: Web Pages, Web Forms, and MVC—
and select an appropriate model for a given project.
Lesson 1
Overview of Microsoft Web Technologies
Before you use ASP.NET MVC 5, you need to know where Microsoft ASP.NET fits in the context of the
entire Microsoft web technologies stack. You should know how ASP.NET websites are hosted in Internet
Information Server (IIS) and Microsoft Azure, and how they run server-side code on web servers, and
client-side code on web browsers, to help provide rich and compelling content.
Lesson Objectives
After completing this lesson, you will be able to:
• Provide an overview of client-side web technologies, including AJAX and JavaScript libraries.
Developer Tools
You can create simple websites with text and
images by using a text editor, such as Notepad.
However, most websites require complex actions
to be performed on the server-side, such as
database operations, email delivery, complex calculations, or graphics rendering. To create such complex,
highly functional, and engaging websites quickly and easily, Microsoft provides the Microsoft Visual Studio
2017 tool. You can use Visual Studio 2017, an Integrated Development Environment (IDE), to create
custom applications based on Microsoft technologies, regardless of whether these applications run on the
web, on desktops, on mobile devices, or by using Microsoft cloud services. Visual Studio 2017 has rich
facilities for designing, coding, and debugging any ASP.NET web application, including MVC applications.
Hosting Technologies
Regardless of the tool you use to build a web application, you must use a web server to host the web
application. When users visit your site, the host server responds by rendering HTML and returning it to the
user’s browser for display. The host server may query a database before it builds the HTML, and the host
server may perform other actions such as sending emails or saving uploaded files. When you finish
building the web application and make it ready for users to access on an intranet or over the Internet, you
must use a fully functional web server such as:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-3
• Microsoft Internet Information Server. IIS is an advanced website hosting technology. You can install
IIS servers on your local network or perimeter network, or employ IIS servers hosted by an Internet
service provider (ISP). IIS can host any ASP.NET, PHP, or Node.js websites. You can scale up IIS to host
large and busy websites by configuring server farms that contain multiple IIS servers, all serving the
same content.
• Microsoft Azure. Microsoft Azure is a cloud platform that provides on-demand services to build,
deploy, host, and manage web applications through Microsoft-managed data centers. When you use
Microsoft Azure services, you need to pay only for the data that your website serves. Also, you need
not worry about building a scalable infrastructure because Microsoft Azure automatically adds
resources as your website grows.
Most websites require a database to manage data such as product details, user information, and
discussion topics. You can choose from the following Microsoft technologies to manage your data:
• Microsoft SQL Server. SQL Server is a premium database server that you can use to host any database
from the simplest to the most complex. SQL Server can scale up to support very large databases and
very large numbers of users. You can build large SQL Server clusters to ensure the best availability and
reliability. Many of the world’s largest organizations rely on SQL Server to host data.
• Microsoft Azure SQL Database. SQL Database is a cloud database platform and a part of Microsoft
Azure. Using SQL Database, you can deploy your database and pay only for the data that you use.
You need not worry about managing your database infrastructure because your database scales up
automatically as your website grows.
• On the user’s web browser. This code responds quickly to user actions, such as mouse clicks, but it is
more limited in what it can accomplish without interacting with the web server.
You need to use different technologies to run server-side code and client-side code.
Server-Side Execution
Microsoft ASP.NET is a server-side web environment that runs server-side .NET code that you write in
Visual Studio 2017. The code accesses the database, renders HTML pages, and returns them to the web
browser. The MVC programming model is a part of ASP.NET. Other server-side technologies include PHP
and Node.js.
Client-Side Execution
Most web browsers can run code written in the JavaScript language. This code is sent to the browser as
text within a rendered HTML page or in a separate .js file. Because JavaScript is local to the browser, it can
respond very quickly to user actions such as clicking, pointing, or dragging.
Many JavaScript libraries are available to accelerate client code development. For example, the popular
jQuery library makes it simple to access page elements and manipulate them by changing their style or
content. When you use such libraries, you can write functions in a few lines that would otherwise require
hundreds of lines of your own JavaScript code.
ASP.NET applications can also use the Asynchronous JavaScript and XML (AJAX) technology on the client
computer. You can use AJAX to update a small section of an HTML page, instead of reloading the entire
page from the server. Such partial page updates help make webpages more responsive and engaging.
Question: If you want to animate a page element, for example, by fading it in, would you write server-
side or client-side code?
MCT USE ONLY. STUDENT USE PROHIBITED
01-4 Exploring ASP.NET MVC 5
Overview of ASP.NET
You can use ASP.NET to develop database-driven,
highly-functional, and scalable dynamic websites
that use client-side and server-side code. You can
create many kinds of website with ASP.NET, for
example, web portals, online shopping sites, blogs,
and wikis.
Programming Models
When you use ASP.NET to build an application,
you are not restricted to a single style of
programming; instead, you can choose from three
different programming models. Each
programming model has a typical structure in the
development environment and stores code in different places in the web hierarchy:
• Web Pages: When you build a site by using Web Pages, you can write code by using the C# or Visual
Basic programming language. If you write C# code, these pages have a .cshtml file extension. If you
write Visual Basic code, these pages have a .vbhtml file extension. ASP.NET runs the code in these
pages on the server to render data from a database, respond to a form post, or perform other actions.
This programming model is simple and easy to learn, and is suited for simple data-driven sites.
ASP.NET includes Web Pages.
• Web Forms: When you build a site by using Web Forms, you employ a programming model with rich
server-side controls and a page life cycle that is not unlike building desktop applications. Built-in
controls include buttons, text boxes, and grid views for displaying tabulated data. You can also add
third-party controls or build custom controls. To respond to user actions, you can attach event
handlers containing code to the server-side controls. For example, to respond to a click on a button
called firstButton, you could write code in the firstButton_Click() event handler.
• MVC: When you build a site by using ASP.NET MVC, you separate server-side code into three parts:
o Model. An MVC model defines a set of classes that represent the object types that the web
application manages. For example, the model for an ecommerce site might include a Product
model class that defines properties such as Description, Catalog Number, Price, and others.
Models often include data access logic that reads data from a database, and writes data to that
database.
o Controllers. An MVC controller is a class that handles user interaction, creates and modifies model
classes, and selects appropriate views. For example, when a user requests full details about a
particular product, the controller creates a new instance of the Product model class and passes it
to the Details view, which displays it to the user.
o Views. An MVC view is a component that builds the webpages that make up the web
application’s user interface. Controllers often pass an instance of a model class to a view. The
view displays properties of the model class. For example, if the controller passes a Product object,
the view might display the name of the product, a picture, and the price.
This separation of model, view, and controller code ensures that MVC applications have a logical
structure, even for the most complex sites. It also improves the testability of the application. Ultimately,
ASP.NET MVC enables more control over the generated HTML than either Web Pages or Web Forms.
Additional Reading: In Lesson 2, Overview of ASP.NET, you will see how to choose the
most appropriate programming model for a given website project.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-5
• Configuration. Using Web.config files, you can configure your web application, regardless of the
programming model. Web.config files are XML files with specific tags and attributes that the ASP.NET
runtime accepts. For example, you can configure database connections and custom error pages in the
Web.config file. In code, you can access the configuration through the System.Web.Configuration
namespace.
• Authentication and Authorization. Many websites require users to log on by entering a user name and
password, or by providing extra information. You can use ASP.NET membership providers to
authenticate and authorize users, and restrict access to content. You can also build pages that enable
users to register a new account, reset a password, recover a lost password, or perform other account
management tasks. Membership providers belong to the System.Web.Security namespace.
• Caching. ASP.NET may take some time to render a complex webpage that may require multiple
database queries or calls to external web services. You can use caching to mitigate this delay. ASP.NET
caches a rendered page in memory, so that it can return the same page to subsequent user requests
without having to render it again from the start. In a similar manner, .NET Framework objects can also
be cached. You can access cached pages by using the System.Runtime.Caching namespace and
configure the caches in Web.config.
2. Compilation to native code. When a page is requested for the first time, the Common Language
Runtime (CLR) compiles MSIL into native code for the server CPU.
This two-stage compilation process enables components written in different languages to work together
and enables many errors to be detected at build time. Note, however, that pages may take extra time to
render the first time they are requested after a server restart. To avoid this delay, you can pre-compile the
website.
When you use the default compilation model, delays can arise when the first user requests a page. This is
because ASP.NET must compile the page before serving it to the browser. To avoid such delays and to
protect source code, use pre-compilation. When you pre-compile a site, all the ASP.NET files, including
controllers, views, and models, are compiled into a single .dll file.
Question: Which of the three programming models do you think provides the most control over the
HTML and JavaScript code that is sent to the browser?
MCT USE ONLY. STUDENT USE PROHIBITED
01-6 Exploring ASP.NET MVC 5
JavaScript
JavaScript is a simple scripting language that has syntax similar to C#, and it is supported by most web
browsers. A scripting language is not compiled. Instead, a script engine interprets the code at run time so
that the web browser can run the code.
Note: Besides JavaScript, Internet Explorer supports VBScript. There are other scripting
languages also, but JavaScript is supported by virtually every web browser. This is not true of any
other scripting language. Unless your target audience is very limited and you have control over
the browser used by your users, you should use JavaScript because of its almost universal
support.
You can include JavaScript code in your ASP.NET pages, irrespective of the programming model you
choose. JavaScript is a powerful language, but can require many lines of code to achieve visual effects or
call external services. Script libraries contain pre-built JavaScript functions that help implement common
actions that you might want to perform on client-side code. You can use a script library, instead of
building all your own JavaScript code from the start; using a script library helps reduce development time
and effort.
Different browsers interpret JavaScript differently. When you develop an Internet site, you do not know
what browsers site visitors use. Therefore, you must write JavaScript that works around browser
compatibility.
jQuery
jQuery is one of the most popular JavaScript libraries. It provides elegant functions for interacting with the
HTML elements on your page and with cascading style sheet (CSS) styles. For example, you can locate all
the <div> elements on a webpage and change their background color by using a single line of code. To
achieve the same result by using JavaScript only, you need to write several lines of code and a
programming loop. Furthermore, the code you write may be different for different browsers. Using
jQuery, it is easier to write code to respond to user actions and to create simple animations. jQuery also
handles browser differences. You can use jQuery to call web services on remote computers and update
the webpage with the results returned.
The jQuery project also includes two other JavaScript libraries that extend the base jQuery library:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-7
• jQuery UI. This library includes a set of widgets that you can use to help build a user interface. There
are date pickers, spinners, dialog boxes, autocomplete text boxes, and other widgets. You can also
apply themes to your jQuery UI widgets to integrate their colors and styles with the website branding.
• jQuery Mobile. This library makes it easy to provide a user interface for mobile devices such as phones
and tablets. It renders HTML by using progressive enhancement. For example, using jQuery Mobile,
you can display rich, advanced controls on advanced mobile devices such as smartphones with large
screens, whereas you can display a simpler UI with the same functionality for older mobile devices
with smaller screens.
Note: There are many other JavaScript libraries such as Prototype, Enyo, Ext, and Dojo
Toolkit. If you find any of these better suited to a particular task, or if you have experience in
developing web applications by using them, you can include them in your ASP.NET pages,
instead of jQuery.
AJAX
AJAX is a technology that enables browsers to communicate with web servers asynchronously by using
the XmlHttpRequest object without completely refreshing the page. You can use AJAX in a page to
update a portion of the page with new data, without reloading the entire page. For example, you can use
AJAX to obtain the latest comments on a product, without refreshing the entire product page.
AJAX is an abbreviation of Asynchronous JavaScript and XML. AJAX is implemented entirely in JavaScript,
and ASP.NET, by default, relies on the jQuery library to manage AJAX requests and responses. The code is
run asynchronously, which means that the web browser does not freeze while it waits for an AJAX
response from the server. Initially, developers used XML to format the data returned from the server. More
recently, however, developers use JavaScript Object Notation (JSON) as an alternative format to XML.
Question: Can you think of any problems that might arise if you include the jQuery library with every
page in your application?
• Deployment Protocols. The advanced Web Deploy protocol, which is built into Visual Studio 2017,
automatically manages the deployment of a website with all its dependencies. Alternatively, you can
use File Transfer Protocol (FTP) to deploy content.
MCT USE ONLY. STUDENT USE PROHIBITED
01-8 Exploring ASP.NET MVC 5
• Centralized Web Farm Management. When you run a large website, you can configure a load-
balanced farm of many IIS servers to scale to large sizes. IIS management tools make it easy to deploy
sites to all servers in the farm and manage sites after deployment.
• High Performance Caches. You can configure ASP.NET to make optimal use of the IIS caches to
accelerate responses to user requests. When IIS serves a page or other content, it can cache it in
memory so that subsequent identical requests can be served faster.
• Authentication and Security. IIS supports most common standards for authentication, including Smart
Card authentication and Integrated Windows authentication. You can also use Secure Sockets Layer
(SSL) to encrypt security-sensitive communications, such as logon pages and pages containing credit
card numbers.
• ASP.NET Support. IIS is a web server that fully supports ASP.NET.
• Other Server-Side Technologies. You can host websites developed in PHP and Node.js on IIS.
Scaling Up IIS
A single web server has limited scalability because it is limited by its processor speed, memory, disk speed,
and other factors. Furthermore, single web servers are vulnerable to hardware failures and outages. For
example, when a single web server is offline, your website is unavailable to users.
You can improve the scalability and resilience of your website by hosting it on a multiple server farm. In
such server farms, many servers share the same server name. Therefore, all servers can respond to browser
requests. A load balancing system such as Windows Network Load Balancing or a hardware-based system
such as Riverbed Cascade, distributes requests evenly among the servers in the server farm. If a server fails,
other servers are available to respond to requests, and thereby, the website availability is not interrupted.
IIS servers are designed to work in such server farms and include advanced management tools for
deploying sites and managing member servers.
Perimeter Networks
Web servers, including IIS, are often located on a perimeter network. A perimeter network has a network
segment that is protected from the Internet through a firewall that validates and permits incoming HTTP
requests. A second firewall, which permits requests only from the web server, separates the perimeter
network from the internal organizational network. Supporting servers, such as database servers, are
usually located on the internal organizational network.
In this configuration, Internet users can reach the IIS server to request pages and the IIS server can reach
the database server to run queries. However, Internet users cannot access the database server or any other
internal computer directly. This prevents malicious users from running attacks and ensures a high level of
security.
IIS Express
Internet Information Server Express does not provide all the features of Internet Information Server on
Windows Server. For example, you cannot create load-balanced server farms by using Internet
Information Server Express. However, it has all the features necessary to host rich ASP.NET websites and
other websites on a single server.
Question: If you wanted to host an ASP.NET site you had written for simple testing by a small team of
developers, which of the preceding web servers would you use as a host?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-9
Microsoft Azure
Microsoft Azure is a part of Microsoft cloud
services for hosting business-critical systems.
When you run code on Microsoft Azure, the code
runs on servers at Microsoft-managed data
centers at locations around the globe. You have
two main advantages when you use Microsoft
Azure to host and deploy your web application:
• Flexible Pricing: With Microsoft Azure, you can choose a pay-as-you-go pricing model, which means
that you only pay for the data that you use. This makes Microsoft Azure very cost-efficient for small
websites. It also makes costs predictable for large websites.
You can use Microsoft Azure to host the following:
• Web Apps. You can host an entire website on Microsoft Azure. Microsoft Azure supports websites
developed in ASP.NET, PHP, or Node.js. You can also deploy websites to Microsoft Azure directly from
Visual Studio 2017.
• API Apps. An API app does not include a user interface like a Web app. Instead, it consists of a set of
methods that you can call, from other software. You can call API apps from mobile devices, desktop
applications, and from website code running on the client-side or the server-side.
• Databases. When you use Internet Information Server to host a website, you can use SQL Server to
store the website database. When you host a website in Microsoft Azure, you can use SQL Database,
which is a cloud-based database service based on SQL Server, to host your database.
• Virtual servers. You can provision entire virtual servers in Microsoft Azure to run business-critical back
office software or use the virtual servers as test environments. Virtual servers in Microsoft Azure can
run Windows Server or Linux.
• Mobile services. If you develop apps for mobile devices such as phones and tablets, you can use
Microsoft Azure to host services that underpin them. Such services can provide user preference
storage, data storage and other functions.
• Media services. When you use Microsoft Azure to host media such as audio and video, it is
automatically available to many types of devices such as computers, mobile phones, and tablets, and
it is encoded in various formats, such as MP4 and Windows Media formats.
Question: How would site visitors know if your site is hosted in Microsoft Azure or IIS Server?
MCT USE ONLY. STUDENT USE PROHIBITED
01-10 Exploring ASP.NET MVC 5
Lesson 2
Overview of ASP.NET
ASP.NET helps you create dynamic websites that use client-side and server-side code. In addition, with
ASP.NET, you are not restricted to a single style of programming; instead, you can choose from three
different programming models: Web Pages, Web Forms, and MVC. These programming models differ
from each other, and they have their own advantages and disadvantages in different scenarios. ASP.NET
also provides many features that you can use, regardless of the programming model you choose.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the features that can be used in all ASP.NET applications, regardless of the chosen
programming model.
Note: If you want to write server-side code in Visual Basic, you use .vbhtml files, instead of
.cshtml files.
You can use Visual Studio 2017 to create Web Pages applications.
The following code example shows HTML and C# code in part of a Web Pages file. The code displays data
from the item object, which is an MVC model class.
<p>Get the best possible value on Northwind specialty foods by taking advantage of these
offers:</p>
@foreach (var item in offers) {
<div class="offer-card">
<div class="offer-picture">
@if (!String.IsNullOrEmpty(item.PhotoUrl)){
<img src="@Href(item.PhotoUrl) alt="@item.Title" />
}
</div>
</div>
}
• It is simple to learn.
• It provides precise control over the rendered HTML.
• Large websites require large numbers of pages, each of which must be coded individually.
• There is no separation of business logic, input logic, and the user interface.
Question: Why should web developers need to take control of the URLs that appear in the Address bar
when a visitor browses a Web Pages site?
• Input controls, such as text boxes, option buttons, and check boxes.
Similarly, when you write custom controls, you store HTML and control markup in an .ascx file. A control
called CustomControl.ascx has a code-behind file called CustomControl.ascx.cs.
Web Forms applications can also contain class files that have the .cs extension.
Note: If you write server-side code in Visual Basic, code-behind files have a .vb extension,
instead of a .cs extension.
• You can use a broad range of highly functional controls that encapsulate a lot of functionality.
• You can display data without writing many lines of server-side code.
• The user interface in the .aspx file is separated from input and business logic in the code-behind files.
• You do not have precise control over markup generated by server-side controls.
• Controls can add large amounts of markup and state information to the rendered HTML page. This
increases the time taken to load pages.
Question: Why should web developers be concerned about the markup and state information that
ASP.NET Web Forms controls add to a rendered HTML page?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-13
MVC Applications
MVC is another programming model available in
ASP.NET. MVC applications are characterized by a
strong separation of business logic, data access
code, and the user interface into Models,
Controllers, and Views.
Models
Each website presents information about different
kinds of objects to site visitors. For example, a
publisher’s website may present information
about books and authors. A book includes
properties such as the title, a summary, and the
number of pages. An author may have properties
such as a first name, a last name, and a short biography. Each book is linked to one or more authors.
When you write an MVC website for a publisher, you would create a model with a class for books and a
class for authors. These model classes would include the properties described and may include methods
such as “buy this book” or “contact this author”. If books and authors are stored in a database, the model
can include data access code that can read and change records.
Models are custom .NET classes and store code in .cs files.
Views
Each website must render HTML pages that a browser can display. This rendering is completed by Views.
For example, in the publishing site, a View may retrieve data from the Book Model and render it on a
webpage so that the user can see the full details. In MVC applications, Views create the user interface.
Views are markup pages that store both HTML and C# code in .cshtml files. This means that they are like
Web Pages, but they include only user interface code. Other logic is separated into Models and
Controllers.
Controllers
Each website must interact with users when they click buttons and links. Controllers respond to user
actions, load data from a model, and pass it to a view, so that it will render a webpage. For example, in the
publishing site, when the user double-clicks a book, he or she expects to see full details of that book. The
Book Controller receives the user request, loads the book model with the right book ID, and passes it to
the Book Details View, which renders a webpage that displays the book. Controllers implement input logic
and tie Models to the right Views.
Controllers are .NET classes that inherit from the System.Web.Mvc.Controller class and store code in .cs
files.
• Views enable the developer to take precise control of the HTML that is rendered.
• You can use the Routing Engine to take precise control of URLs.
• Business logic, input logic, and user interface logic are separated into Models, Controllers, and Views.
• Unit testing techniques and Test Driven Development (TDD) are possible.
• MVC forces you to separate your concerns (models, views, and controllers). Some programmers may
find this challenging.
• You cannot visually create a user interface by dragging controls onto a page.
• You must have a full understanding of HTML, CSS, and JavaScript to develop Views.
Question: When a user makes a request for a particular product in your product catalog, which
component receives the request first: a model, a controller, or a view?
Database Front-End
Your organization has its own customer
relationship management system that stores data
in a SQL Server database. Your team of developers
wrote the user interface in Visual Studio 2017 as a
desktop application. The directors now require
that all computers should be able to access the
application even when the desktop client
application is not installed. Because all computers have a browser, you have decided to write a web
application in ASP.NET to enable this.
E-Commerce Site
You are a consultant for a large software organization. You have been asked to architect an e-commerce
website that will enable customers to browse the entire catalog of software packages, download the
packages, and purchase licenses. The company has a large team of developers who are familiar with .NET
object-oriented programming. The company policy is to use Test Driven Development for all software.
Configuration
When you configure an ASP.NET site, you can
control how errors are handled, how the site
connects to databases, how user input is validated,
and many other settings. You can configure
ASP.NET sites by creating and editing Web.config
files. The Web.config file in the root folder of your site configures the entire site, but you can override this
configuration at lower levels by creating Web.config files in sub-folders.
Web.config files are XML files with a set of elements and attributes that the ASP.NET runtime accepts.
If you need to access configuration values at runtime in your server-side .NET code, you can use the
System.Web.Configuration namespace.
MCT USE ONLY. STUDENT USE PROHIBITED
01-16 Exploring ASP.NET MVC 5
Authentication
Many websites identify users through authentication. This is usually done by requesting and checking
credentials such as a user name and password, although authentication can be done by using more
sophisticated methods, such as using smart cards. Some sites require all users to authenticate before they
can access any page, but it is common to enable anonymous access to some pages and require
authentication only for sensitive or subscription content.
ASP.NET supports several mechanisms for authentication. For example, if you are using Internet Explorer
on a Windows computer, ASP.NET may be able to use Integrated Windows authentication. In this
mechanism, your Windows user account is used to identify you. When you build Internet sites, you cannot
be sure that users have Windows, a compatible browser, or an accessible account, so Forms
Authentication is often used. Forms Authentication is supported by many browsers and it can be
configured to check credentials against a database, directory service, or other user account stores.
When you have more than a few users, you may want to group them into roles with different levels of
access. For example, you might create a “Gold Members” role containing user accounts with access to the
best special offers. ASP.NET role providers enable you to create and populate roles with the minimum of
custom code.
You can enable access to pages on your website for individual user accounts or for all members of a role.
This process is known as authorization.
State Management
Web servers and web browsers communicate through HTTP. This is a stateless protocol in which each
request is separate from requests before and after it. Any values from previous requests are not
automatically remembered.
However, when you build a web application, you must frequently preserve values across multiple page
requests. For example, if a user places a product in a shopping cart, and then clicks “Check Out”, this is a
separate web request, but the server must preserve the contents of that shopping cart; otherwise, the
shopping cart will be emptied and the customer will buy nothing. ASP.NET provides several locations
where you can store such values or state information across multiple requests.
Caching
An ASP.NET page is built dynamically by the ASP.NET runtime on the web server. For example, in a Web
Pages application, the runtime must execute the C# code in the page to render HTML to return it to the
browser. That C# code may perform complex and time-consuming operations. It may run multiple queries
against a database or call services on remote servers. You can mitigate these time delays by using
ASP.NET caches.
For example, you can use the ASP.NET page cache to store the rendered version of a commonly
requested page in the memory of the web server. The front page of your product catalog may be
requested hundreds or thousands of times a day by many users. If you cache the page in memory the first
time it is rendered, the web server can serve it to most users very rapidly, without querying the database
server and building the page from scratch.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-17
Question: Can you think of other facilities that all ASP.NET applications might need, regardless of the
programming model they use?
MCT USE ONLY. STUDENT USE PROHIBITED
01-18 Exploring ASP.NET MVC 5
Lesson 3
Introduction to ASP.NET MVC 5
You need to know how models, views, and controllers work together to render HTML, and how the
structure of MVC applications determines the display of information in a Visual Studio 2017 project. You
can examine the new features of MVC 5, included in ASP.NET, to build rich and engaging applications.
Lesson Objectives
After completing this lesson, you will be able to:
• Explore the main features of an ASP.NET MVC 5 web application in Visual Studio.
Controllers inherit from the System.Web.Mvc.Controller base class. Actions usually return a
System.Web.Mvc.ActionResult object.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-19
The following lines of code are part of an ASP.NET MVC 5 view and use the Razor syntax. The @ symbol
delimits server-side code.
<fieldset>
<legend>Comment</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Subject)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Subject)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Body)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Body)
</div>
</fieldset>
Often, the view displays properties of a model class. In the preceding code example, the Subject property
and Body property are incorporated into the page.
2. The MVC routing engine examines the request and determines that it should forward the request to
the Product Controller and the Display action.
3. The Display action in the Product Controller creates a new instance of the Product model class.
4. The Product model class queries the database for information about the product with ID “1”.
5. The Display action also creates a new instance of the Product Display View and passes the Product
Model to it.
6. The Razor view engine runs the server-side code in the Product Display View to render HTML. In this
case, the server-side code inserts properties such as Title, Description, Catalog Number, and Price into
the HTML.
Question: If you wanted to write some code that renders data from your products catalog into an HTML
table, would you place that code in a model, a view, a controller, or a JavaScript function?
MCT USE ONLY. STUDENT USE PROHIBITED
01-20 Exploring ASP.NET MVC 5
Demonstration Steps
You will find the steps in the “Lesson 3: Introduction to ASP.NET MVC 5“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD01_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-21
• How does the developer set a connection string and data provider?
• How does the developer impose a consistent layout, with Adventure Works branding and menus, on
all pages in the web application?
• How does the developer set a cascading style sheet with a consistent set of color, fonts, borders, and
other styles?
• How does the developer add a new page to the application and apply the layout and styles to it?
Objectives
After completing this lab, you will be able to:
• Describe and compare the three programming models available in ASP.NET.
• Describe the structure of each web application developed in the three programming models—Web
Pages, Web Forms, and MVC.
• Select an appropriate programming model for a given set of web application requirements.
Lab Setup
Estimated Time: 80 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD01_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD01_LAK.md.
Question: Which of the three programming models has the simplest method of applying a
single layout across multiple pages?
Question: Which of the three programming models has the simplest method of building a
user interface?
Question: Which of the application programming models will you recommend for the photo
sharing application: Web Pages, Web Forms, or MVC?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 01-23
Review Question
Question: Which of the shared features of ASP.NET can you use in Web Pages, Web Forms,
and MVC applications to increase the speed with which frequently-requested pages are
returned to the browser?
Best Practices
• Use Web Pages when you have simple requirements or have developers with little experience of
ASP.NET.
• Use Web Forms when you want to create a user interface by dragging controls from a toolbox onto
each webpage or when your developers have experience of Web Forms or Windows Forms.
• Use MVC when you want the most precise control over HTML and URLs, when you want to cleanly
separate business logic, user interface code, and input logic, or when you want to perform Test Driven
Development.
Additional Reading: For more information about ASP.NET, including forums, blogs, and
third-party tools, visit the official ASP.NET site:
http://go.microsoft.com/fwlink/?LinkID=293681&clcid=0x409
MCT USE ONLY. STUDENT USE PROHIBITED
01-24 Exploring ASP.NET MVC 5
MCT USE ONLY. STUDENT USE PROHIBITED
02-1
Module 2
Designing ASP.NET MVC 5 Web Applications
Contents:
Module Overview 02-1
Module Overview
Microsoft ASP.NET MVC 5 is a programming model that you can use to create powerful and complex web
applications. However, all complex development projects, and large projects in particular, can be
challenging and intricate to fully understand. Without a complete understanding of the purposes of a
project, you cannot develop an effective solution to the customer’s problem. You need to know how to
identify a set of business needs and plan an MVC web application to meet those needs. The project plan
that you create assures stakeholders that you understand their requirements and communicates the
functionality of the web application, its user interface, structure, and data storage to the developers who
will create it. By writing a detailed and accurate project plan, you can ensure that the powerful features of
MVC are used most effectively to solve a customer’s business problems.
Objectives
After completing this module, you will be able to:
• Plan the overall architecture of an MVC 5 web application and consider aspects such as state
management.
• Plan the models, controllers, and views that are required to implement a given set of functional
requirements.
MCT USE ONLY. STUDENT USE PROHIBITED
02-2 Designing ASP.NET MVC 5 Web Applications
Lesson 1
Planning in the Project Design Phase
Before you and your team of developers plan a Model-View-Controller (MVC) web application or write
any code, you must have a thorough understanding of two things: the business problem you are trying to
solve and the ASP.NET components that you can use to build a solution. Before designing a web
application architecture and its database, you should know how to identify the requirements that
potential users of a web application have.
Lesson Objectives
After completing this lesson, you will be able to:
• Determine the functional requirements and business problems when building web applications.
• Explain how to plan the database design when building a web application.
Some project development methodologies include the waterfall model, the iterative development model,
the prototyping model, the agile software development model, extreme programming, and test-driven
development.
Waterfall Model
The waterfall model is an early methodology that defines the following phases of a project:
• Feasibility analysis. In this phase, planners and developers study and determine the approaches and
technologies that can be used to build the software application.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-3
• Requirement analysis. In this phase, planners and analysts interview the users, managers,
administrators, and other stakeholders of the software application to determine their needs.
• Application design. In this phase, planners, analysts, and developers record a proposed solution.
• Coding and unit testing. In this phase, developers create the code and test the components that make
up the system individually.
• Integration and system testing. In this phase, developers integrate the components that they have
built and test the system as a whole.
• Deployment and maintenance. In this phase, developers and administrators deploy the solution so
that users can start using the software application.
The waterfall model classifies the development project into distinct phases with a clear definition of
deliverables for each phase. The model also emphasizes the importance of testing. However, the customer
does not receive any functional software for review until late in the project. This makes it difficult to deal
with changes to the design in response to beta feedback or manage altered circumstances.
In an iterative project, you can perform corrective action at the end of each iteration. These corrections
might reflect a better understanding of the business problems, insightful user feedback, or a better
understanding of the technologies that you used to build the solution. Because requirements are added at
the end of each iteration, iterative projects require a great deal of project management effort and
frequently feature an overrun of planned efforts and schedule.
Prototyping Model
The prototyping model is suitable for a project where you begin with a few or meagerly defined business
requirements. This situation occurs when the customers or stakeholders have only a vague understanding
of their needs and how to solve them. In this approach, developers create a simplified version of the
software application, and then seek feedback from stakeholders. This feedback on the prototype is used
to define the detailed requirements, which developers use in the next iteration to build a solution that
matches the needs of stakeholders to better help them perform their jobs.
After two or more iterations, when both stakeholders and developers reach a consensus on the
requirements, a complete solution is built and tested. The prototyping model, however, can lead to a
poorly-designed application because at no stage in the project is there a clear focus on the overall
architecture.
• Incremental development. Software is developed in rapid cycles that build on earlier cycles. Each
iteration is thoroughly tested.
• Emphasis on people and interactions. Developers write code based on what people do in their role,
rather than what the development tools are good at.
MCT USE ONLY. STUDENT USE PROHIBITED
02-4 Designing ASP.NET MVC 5 Web Applications
• Emphasis on working software. Instead of writing detailed design documents for stakeholders,
developers write solutions that stakeholders can evaluate at each iteration to validate if it solves a
requirement.
• Close collaboration with customers. Developers discuss with customers and stakeholders on a day-to-
day basis to check requirements.
Extreme Programming
Extreme programming evolved from agile software development. In extreme programming, the
preliminary design phase is reduced to a minimum and developers focus on solving a few critical tasks. As
soon as these critical tasks are finalized, developers test the simplified solution and obtain feedback from
stakeholders. This feedback helps developers identify the detailed requirements, which evolve over the
project life cycle.
Extreme programming defines a user story for every user role. A user story describes all the interactions
that a user with a specific role might perform with the completed application. The collection of all the user
stories for all user roles describes the entire application.
In extreme programming, developers often work in pairs. One developer writes the code and the other
developer reviews the code to ensure that it uses simple solutions and adheres to best practices. Test-
driven development is a core practice in extreme programming.
Additional Reading: For more information about the extreme programming model, go to
http://go.microsoft.com/fwlink/?LinkID=288945&clcid=0x409.
• Behavior diagrams. These diagrams depict the behavior of users, applications, and application
components.
• Interaction diagrams. These diagrams are a subset of behavior diagrams that focus on the interactions
between objects.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-5
• Structure diagrams. These diagrams depict the elements of an application that are independent of
time. This means they do not change through the lifetime of the application.
Question: What aspects of agile software development and extreme programming might be of concern
to customers? What aspects might reassure them?
Gathering Requirements
When a project is commissioned, you need a
vision of the solution. The vision can often be
vague and require in-depth investigation before
you can add details and ensure that all
stakeholders’ requirements are covered by the
web application that you build. These
requirements can be of two types:
• Functional requirements. These requirements
describe how the application behaves and
responds to users. Functional requirements
are often called behavioral requirements.
They include:
o User interface requirements. These requirements describe how the user interacts with an
application.
o Usage requirements. These requirements describe what a user can do with the application.
o Business requirements. These requirements describe how the application will fulfill business
functions.
• Technical requirements. These requirements describe technical features of the application and relate
to availability, security, or performance. These requirements are sometimes called non-functional or
non-behavioral requirements.
You usually gather requirements by interviewing stakeholders such as users, administrators, other
developers, board members, budget holders, and team managers. Each of these groups will have a
different set of priorities that the application needs to fulfill.
A usage scenario is a specific real-world example, with names and suggested input values, of an
interaction between the application and a user. The following is a simple example:
1. Roger Lengel clicks the Add Photo link on the main site menu.
2. Roger provides the input, RogerL, in the User name box and the password in the Password box to
authenticate on the site.
6. The web application stores the new photo and displays the photo gallery to Roger.
MCT USE ONLY. STUDENT USE PROHIBITED
02-6 Designing ASP.NET MVC 5 Web Applications
A use case is similar to a usage scenario, but is more generalized. Use cases do not include user names or
input values. They describe multiple paths of an interaction, which depends on what the user provides as
input or other values. The following is a simple example:
1. The user clicks the Add Photo link on the main site menu.
2. If the user is anonymous, the logon page is shown and the user provides credentials.
8. The web application stores the new photo and displays the photo gallery to the user.
Note: Similar to verbal descriptions, you can use UML Use Case diagrams to record the use
cases for your web application.
By analyzing usage scenarios and use cases, you can identify functional requirements of all types. For
example, from the preceding use case, you can identify the following user interface requirement: The
webpage that enables users to create a new photo must include Title and Description text boxes, a file
input control for the photo file, and an Upload button to save the photo.
• Just-in-time modeling. Before writing code that implements a use case, a developer discusses it with
the relevant users. At this point, the developer adds full details to the use case. In an agile
development project, developers talk to users and other stakeholders at all times, and not just at the
beginning and end of the project.
• Acceptance testing. An acceptance test is a test that the application must pass for all stakeholders to
accept and sign off the application. When you identify a functional requirement, you can also specify
a corresponding acceptance test that must be run to ensure that the requirements are met.
• Users can upload photos and give new photos a title and a description.
User stories contain just the minimal details to enable developers to estimate the effort involved in
developing it. Extreme programmers discuss each user story with stakeholders just before they write code
to implement each user story.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-7
Question: If a customer asks you to ensure 95% availability, is this a functional requirement or a technical
requirement?
Logical Modeling
You can begin your data design at a high level by creating UML Domain Model diagrams and Logical
Data Model (LDM) diagrams.
A domain model diagram, also known as a conceptual data model, shows the high-level conceptual
objects that your web application manages. For example, in an e-commerce web application, the domain
model includes the concepts of customers, shopping carts, and products. The domain model does not
include details of the properties each concept has, but shows the relationships between concepts. Use the
domain model to record your initial conversations with stakeholders.
In essence, an LDM is a domain model diagram with extra details added. You can use LDM diagrams to fill
in more details, such as properties and data types, for the concepts that you defined in the domain model.
Note that the objects in the LDM do not correspond to tables in the database. For example, the shopping
cart object may display data from both the customer database and product database tables.
• Tables. These are the fundamental storage objects in a database. When you define a table, you need
to specify the columns that each table has. For each column, you must define a data type such as
integer, string, usually the nvarchar type in SQL Server, or date and time. You should also define
the primary key for the table—the value of this column uniquely identifies each record and is
essential for defining the relationships with records in other tables.
• Views. These are common presentations of data in tables and are based on queries. For example, a
view can join two tables, such as a products table and a stock levels table.
• Stored procedures. These are common sequences of database operations that you define in the
database. Some operations are complex and might involve a complex transformation of the data. You
can define a stored procedure to implement such a complex routine.
• Security. You need to consider how the web application will authenticate with the database server
and how you will authorize access to each database table.
In UML, a physical data model is a diagram that depicts tables, columns, data types and relationships
between tables.
MCT USE ONLY. STUDENT USE PROHIBITED
02-8 Designing ASP.NET MVC 5 Web Applications
If your project database is administered by the DBA team, it is essential to communicate well with them.
You need to consult with DBAs for their requirements. They frequently impose a list of technical
requirements that other stakeholders may not understand. As you build and deploy the web application,
DBAs are responsible for creating databases on the right servers or clusters and assigning permissions.
DBAs are critical contributors in delivering the web application.
In agile development and extreme programming, the database design changes throughout the project
until deployment. Therefore, developers should be able to alter the database whenever necessary without
consulting DBAs or complying with complex data policies. For this reason, you should use a separate
database hosted on a dedicated development server.
In some cases, the development project works with a database that already exists. For example, you may
be developing a web application that presents and edits information from the company employee
database on the intranet. In such cases, the database does not change as the code is developed, but
functional and technical requirements may still change. You should copy the database to an isolated
development database server to ensure that your developing code does not erroneously modify business-
critical data.
Question: You want to implement a shopping cart in your web application. How many logical data
models are required? How many database tables are required?
• Business logic layer. Components in this layer implement high-level business objects such as products,
or customers. If you are building an MVC web application, models make up your business logic layer.
• Data access layer. Components in this layer implement database access operations and abstract
database objects, such as tables, from business objects. For example, a product business object may
include data from both the Products and StockLevels database tables. If you are building an MVC web
application, models often make up both business logic and data access layers. However, with careful
design and coding practices, it is possible to refactor code to separate these layers.
If you implement such a layered architecture in your web application, you can host each layer on separate
servers. Often, for example, the presentation layer is hosted on one or more IIS servers, the business logic
and data access layers are hosted on dedicated middle-tier servers, and the database is hosted on a
dedicated SQL Server. This approach has the following advantages:
• You can specify server hardware that closely matches each role. For example, a server that hosts
business logic components requires good memory and processing resources.
• You can dedicate multiple servers to each role to ensure that a single server failure does not cause an
interruption in service.
• Only the web servers must be on the perimeter network. Both middle-tier servers and database
servers can be protected by two firewalls without direct access from the Internet.
• Alternatively, you can host middle-tier layers and databases on a cloud service, such as Windows
Azure.
The communication of information and security is performed in different ways between the various layers:
• Between the browser and presentation layer web server. In any web application, the web browser,
where the presentation layer runs, communicates with the web server by using HTTP. If
authentication is required, it is often performed by exchanging plain text credentials. You can also use
Secure Sockets Layer (SSL) to encrypt this sensitive communication.
• Between the web server and the middle-tier server. The communication and security mechanisms used
for communication between the web server and the middle-tier server depends on the technology
that you use to build the business logic components:
o Web services: If you implement business objects and data access classes as web services, the
presentation layer components communicate with the web services by using HTTP. You can
perform authentication by using the Kerberos protocol that is a part of Windows Integrated
Authentication or by using plain text encrypted with SSL.
o Windows Communication Foundation (WCF) services: If you implement business objects and
data access classes as WCF services, you can choose between two hosting mechanisms. You can
host the WCF services within IIS, in which case, HTTP is the transport mechanism and SSL is the
security mechanism. You can also host the WCF services within a Windows Process Activation
MCT USE ONLY. STUDENT USE PROHIBITED
02-10 Designing ASP.NET MVC 5 Web Applications
Service (WAS), in which case, you can use TCP, Microsoft Message Queuing (MSMQ), or named
pipes as the transport mechanism.
• Between middle-tier server and database. The middle-tier server sends T-SQL queries to the database
server, which authenticates against the database by using the required credentials that are often
included in the connection string.
Note: Web services and WCF services are covered in detail in Course 20487C: Developing
Windows Azure and Web Services.
Question: What are the advantages of writing middle-tier components as WCF services and not web
services?
• User identity. Some sites authenticate users to provide access to members-only content. If the user
identity is lost between page requests, the user must re-enter the credentials for every page.
• Shopping carts. If the content of a shopping cart is lost between page requests, the customer cannot
buy anything from your web application.
In almost all web applications, state storage is a fundamental requirement. ASP.NET provides several
locations where you can store state information, and simple ways to access the state information.
However, you must plan the use of these mechanisms carefully. If you use the wrong location, you may
not be able to retrieve a value when you expect to. Furthermore, poor planning of state management
frequently results in poor performance.
In general, you should be careful about maintaining large quantities of state data because it either
consumes server memory, if it is stored on the server, or slows down the transfer of the webpage to the
browser, if it is included in a webpage. If you need to store state values, you can choose between client-
side state storage or server-side state storage.
• Cookies. Cookies are small text files that you can pass to the browser to store information. A cookie
can be stored:
o In the client computer memory, in which case, it preserves information only for a single user
session.
o On the client computer hard disk drive, in which case, it preserves information across
multiple sessions.
Most browsers can store cookies only up to 4,096 bytes and permit only 20 cookies per website.
Therefore, cookies can be used only for small quantities of data. Also, some users may disable cookies
for privacy purposes, so you should not rely on cookies for critical functions.
• Query strings. A query string is the part of the URL after the question mark and is often used to
communicate form values and other data to the server. You can use the query string to preserve a
small amount of data from one page request to another. All browsers support query strings, but some
impose a limit of 2,083 characters on the URL length. You should not place any sensitive information
in query strings because it is visible to the user, anyone observing the session, or anyone monitoring
web traffic.
Note: In ASP.NET Web Forms applications, View State, Control State, and Hidden Fields can
be used to store state information in the rendered HTML that the server sends to the client. These
mechanisms are not available in MVC web applications because they do not use Web Forms
controls.
• TempData. This is a state storage location that you can use in MVC applications to store values
between one request and another. You can store values by adding them to the TempData collection.
This information is preserved for a single request only and is designed to help maintain data across a
webpage redirect. For example, you can use it to pass an error message to an error page.
• Application State. This is a state storage location that you can use to store vales for the lifetime of the
application. The values stored in application state are shared among all users. You can store values by
adding them to the Application collection. If the web server or the web application is restarted, the
values are destroyed. The Application_Start() procedure in the Global.asax file is an appropriate
place to initialize application state values. Application state is not an appropriate place to store user-
specific values, such as preferences, because if you store a preference in application state, all users
share the same preference, instead of having their own unique value.
• Session state. The Session collection stores information for the lifetime of a single browser session
and values stored here are specific to a single user session; they cannot be accessed by other users. By
default, if the web server or the web application is restarted, the values are destroyed. However, you
can configure ASP.NET to store session state in a database or state server. If you do this, session state
can be preserved across restarts. Session state is available for both authenticated users and
anonymous users. By default, session state uses cookies to identify users, but you can configure
ASP.NET to store session state without using cookies.
If you choose to use these server memory locations, ensure that you estimate the total volume of state
data that may be required for all the concurrent users that you expect to manage. Application state values
are stored only once, but session state values are stored once for each concurrent user. Specify server
MCT USE ONLY. STUDENT USE PROHIBITED
02-12 Designing ASP.NET MVC 5 Web Applications
hardware that can easily manage this load, or move state data into the following server hard disk drive-
based locations.
• Profile properties. If your site uses an ASP.NET profile provider, you can store user preferences in
profiles. Profile properties are persisted to the membership database, so they will be kept even if the
web application or web server restarts.
• Database tables. If your site uses an underlying database, like most sites do, you can store state
information in its tables. This is a good place to store large volumes of state data that cannot be
placed in server memory or on the client computer. For example, if you want to store a large volume
of session-specific state information, you can store a simple ID value in the Session collection and use
it to query and update a record in the database.
Remember that state data is only one form of information that an ASP.NET application places in server
memory. For example, caches must share memory with state data.
Question: You show the visitors of your website a choice of countries. When they pick a state, you want
to redirect them to a page that shows a map of that state. You will not use the name of the chosen
country that the user selected after this. Which location should you use to store the name of the chosen
country?
The preferred language that users choose is available as the language code in the HTTP Header of the
user’s browser. This is the value that you respond to, so as to globalize your site. Alternatively, you can
provide a control, such as a drop-down list, in which users can choose their preferred language. This is a
good example of a user-preference that you can store in the session state.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-13
Resource files can also have a neutral culture. This means that the file applies to any region in a given
language. For example the Index.es.resx file applies Spanish terms, regardless of the regional code that
has been chosen.
You should also create corresponding default resource files, without any language code in the file name,
such as Index.resx. These files are used when a preferred language is not specified.
When you use resource files to localize a site, each view applies, regardless of the preferred language. You
must insert extra Razor code in the view to take text values from a resource file. This can reduce the
readability of view files because all the rendered text comes from resource files. However, supporting new
languages is easier, because you only need to add a new resource file for each language that can be
created by a professional translator.
Lesson 2
Designing Models, Controllers, and Views
Models, controllers, and views are the fundamental building blocks of an MVC 5 web application. In a
complex site, there may be hundreds of models, views, and controllers. You need to manage these objects
and plan your application well, so that it is easy to manage the organization and internal structure during
development. A thorough plan ensures that you detect any incorrect code and debug problems rapidly.
Lesson Objectives
After completing this lesson, you will be able to:
Designing Models
A fundamental activity in the MVC design process
is designing a model. Each model class within the
model represents a kind of object that your
application manages. You cannot plan for
controllers and views until you understand the
structure and design of the model.
1. The user clicks the Add Photo link on the main site menu.
2. If the user is anonymous, the logon page is shown and the user provides credentials.
3. If the credentials are correct, the CreatePhoto view is displayed.
This example includes the following objects, each of which requires a model class:
• User. The User model class must include properties to store credentials, such as the user name and
the password.
• Photo. The Photo model class must include the Title and Description properties.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-15
Other use cases similarly help you add new model classes or new properties to the User and Photo model
classes.
Entity Framework
Entity Framework is an Object Relational Mapping (ORM) framework for .NET Framework-based
applications. An ORM framework links database tables and views to classes that a developer can program
against, by creating instances or calling methods. Entity Framework has been a part of ADO.NET since
.NET Framework 3.5.
When you use Entity Framework in your MVC web application, it links tables and views to the model
classes that you have planned. You do not need to write SQL code to query or update database tables
because Entity Framework does this for you. Entity Framework is well integrated with the Language
Integrated Query (LINQ) language.
If you plan to use Entity Framework for data access, you should decide on how the database will be
created during the planning phase:
• Database-First. Use the Entity Framework in the database-first mode when you have a pre-existing
database to work with. This may happen because you already have data from an earlier system or
because a DBA has designed the database for you. You can also choose this mode if you are familiar
with creating databases in a database administration tool, such as Microsoft SQL Server Management
Studio. When you use this mode, you have to specify the database connection string. Entity
Framework connects to the database and examines the database schema. It creates a set of classes for
you to use for data access.
• Model-First. Use Entity Framework in the model-first mode when you do not have a pre-existing
database and prefer to design your model in Visual Studio. You can use the Entity Designer tool to
name, configure, and link your model classes. This creates XML files that Entity Framework uses both
to create model classes and to create the database with its tables and relationships.
MCT USE ONLY. STUDENT USE PROHIBITED
02-16 Designing ASP.NET MVC 5 Web Applications
• Code-First. Use Entity Framework in the code-first mode when you have no pre-existing database and
prefer to design your models entirely in C# code. Your code must include DBContext and DBSet
objects—these correspond to the database and its tables. When you run the application for the first
time, Entity Framework creates the database for you.
In an MVC project, this means that you identity the model names and relationships during the design
phase. You can record these on a Domain Model UML diagram. However, you can leave details such as
property names and data types to be finalized in the development phase, along with the complete LDM
diagrams.
Entity Framework lets you work in the Agile or Extreme Programming styles. For example, the framework
can update the database when the model changes. Alternatively, the framework can update the model
when the database changes. Entity Framework can perform these updates in any Entity Framework mode.
Designing Controllers
In an ASP.NET MVC web application, controllers
are .NET Framework-based classes that inherit
from the System.Web.Mvc.Controller base class.
They implement input logic—this means that they
receive input from the user in the form of HTTP
requests and select both the correct model and
view to use, to formulate a response.
However, for each controller there can be many actions—each action is implemented as a method in the
controller and usually returns a view. You often require separate actions for GET and POST HTTP request
verbs. Similar to designing a model, you can identify the actions to write in each controller by examining
the use cases you gathered during analysis. For example, consider the following use case shared earlier.
1. The user clicks the Add Photo link on the main site menu.
2. If the user is anonymous, the logon page is shown and the user provides credentials.
8. The web application stores the new photo and displays the photo gallery to the user.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-17
You have already identified Photo and User model classes from this use case. Adhering to the MVC
convention, you should create a PhotoController and a UserController. The use case shows that the
following actions are needed for each controller.
Photo AddPhoto (GET) The AddPhoto action for GET requests creates a new
instance of the Photo model class, sets default values such as
the created date, and passes it to the correct view.
AddPhoto (POST) The AddPhoto action for POST requests calls the Photo
model class methods to save the photo values to the
database and redirects the browser to the DisplayGallery
action.
DisplayGallery (GET) The DisplayGallery action for GET requests displays all the
photos stored in the database.
User Logon (GET) The Logon action for GET requests displays a view that an
anonymous user can enter credentials into.
Logon (POST) The Logon action for POST requests checks user credentials
against the membership database. If the credentials are
correct, the Logon action authenticates and redirects the
user to the originally requested page.
Designing Views
The user interface is a vital component of any
system because it is the part that the users,
budget holders, and other stakeholders see and
interact with. Users are most interested in getting
this part of the application right and frequently
have the most to say about its design. As a
developer, you have a chance to impress your
users by designing and implementing a
sophisticated user interface, which may result in
more business.
As you plan views, you should also consider parts of the user interface that appear on all pages. For
example, the company logo, main site menu, links to legal information, and logon controls may need to
appear on every page. You can place these user interface components in a template view to create a
consistent look and feel across pages.
Note: Template views in ASP.NET MVC web applications perform the same role as master
pages in ASP.NET Web Forms applications.
Some user interface components do not appear on all pages, but are re-used on several pages. For
example, comments may be displayed in a single photo display, on the gallery, or on other pages. By
creating a partial view, you can create a re-usable user interface element that can appear in many
locations in this manner, without duplicating code.
Creating Wireframes
A common technique to discuss and plan the user interface for your application is to create wireframe
diagrams. These are simplified layouts that show where the elements will appear on the final webpages.
They are intended to communicate to users the essential functional parts of the user interface, but do not
include graphics, logos, or colors. It is not necessary to create a wireframe model for every view in your
application, but for only the most important ones.
You can begin a wireframe diagram by sketching it on a whiteboard, in conversation with a user. Many
tools are available to create more formal versions—for example, Microsoft Visio has excellent wireframe
drawing capabilities.
• An MVC model that you can use to implement the desired functionality.
• One or more controllers and controller actions that respond to users actions.
Objectives
After completing this lab, you will be able to:
• Design an ASP.NET MVC 5 web application that meets a set of functional requirements.
• Record the design in an accurate, precise, and informative manner.
Lab Setup
Estimated Time: 40 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD02_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD02_LAK.md.
Question: What model classes should be created for the photo sharing application based on the
initial investigation?
Question: What controllers should be created for the photo sharing application based on the
initial investigation?
Question: What views should be created for the photo sharing application?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 02-21
Review Question
Question: You want to support both English and Spanish in your web application. You have
both Spanish-speaking and English-speaking developers and want to ensure that views
remain readable as easily as possible. Should you use multiple view files or multiple resource
files to globalize your site?
Furthermore, when working with agile development and extreme programming projects, project
managers must take care to avoid project creep or scope-creep. This occurs when people add new
requirements when development takes place. Project creep results in projects that are over-budget and
late.
Tools
Microsoft Office Visio: You can use Visio to create all types of UML software design diagrams, including
Domain Model diagrams and LDMs. You can also use it to create wireframes.
Visual Studio 2017: You can create class diagrams such as LDMs in Visual Studio 2017.
Best Practices
• In Agile Development and Extreme Programming projects, developers discuss with users and
stakeholders throughout development to ensure that their code will meet changing
requirements. Even if you are not formally using these methodologies, it is good practice to
regularly communicate with users.
• When you design an ASP.NET MVC web application, start with the model, and then plan
controllers, actions, and views. The controllers, actions, and views that you create each
depend on the model.
Module 3
Developing ASP.NET MVC 5 Models
Contents:
Module Overview 03-1
Module Overview
Most web applications need to interact with various types of data or objects. An e-commerce application,
for example, helps manage products, shopping carts, customers, and orders. A social networking
application might help manage users, status updates, comments, photos, and videos. A blog is used to
manage blog entries, comments, categories, and tags. When you write an MVC web application, you
create an MVC model to model the data for your web application. Within this model, you create a model
class for each type of object. The model class describes the properties of each type of object and can
include business logic that matches business processes. Therefore, the model is a fundamental building-
block in an MVC application and a good place to start when you write code. Models interact with the
information store that underlies your site, which is usually a database. Therefore, you need to understand
data access techniques and technologies to write models. In this module, you will see how to create the
code for models and access data by using Entity Framework and LINQ.
Objectives
After completing this module, you will be able to:
• Add a model to an MVC application and write code in it to implement the business logic.
• Create a new SQL Azure database to store data for the web application.
MCT USE ONLY. STUDENT USE PROHIBITED
03-2 Developing ASP.NET MVC 5 Models
Lesson 1
Creating MVC Models
An MVC model is a collection of .NET Framework classes. When you create a model class, you define the
properties and methods that suit the kind of object the model class describes. You can describe these
properties in code so that MVC can determine how to render them in a webpage and how to validate
user input. You need to know how to create and describe models, and how to modify the manner in
which MVC creates model class instances when it runs your web application.
Lesson Objectives
After completing this lesson, you will be able to:
Developing Models
Every website presents information about various
types of objects. In your web application, you
need to define model classes for these objects.
When you implement a functional requirement in
your web application, you usually start by creating
a model class. The model class will probably be
revised when you create the controller and views
for the model, and then later during the iterations
that happen during the project. If you follow the
Agile Development model or Extreme
Programming, you begin with a simple
understanding of the class—perhaps its name and
a few properties. Then, you discuss with users and add details to the planned model class with the
complete set of properties and its relationships to other classes. When developing the model, you can
refer to use cases or user stories to ensure that these model details are correct.
When you feel that you fully understand the requirements for a model, you can write model classes to
implement the requirements. The following lines of code illustrate how to create an example model class
named Photo.
Notice that the model class does not inherit from any other class. Also, notice that you have created
public properties for each property in the model and included the data type, such as integer or string in
the declaration. You can create read-only properties by omitting the set; keyword.
The Photo class includes a property called Comments. This is declared as a collection of Comment
objects and implements one side of the relationship between photos and comments.
The following lines of code illustrate how you can implement the Comment model class.
Notice that the Comment class includes a PhotoID property. This property stores the ID of the Photo
that the user commented on, and it ties the comment to a single photo. Also, notice that the Comment
class includes a Photo property, which returns the Photo object that the comment relates to. These
properties implement the other side of the relationship between photos and comments. The instances of
model classes are usually created in a controller action and passed to a view to display.
The following code example shows how a controller action can create a new photo object from the photo
model class and pass it to the Display view.
In the Display view, you can render the Title property of a photo by using the Model object in the Razor
code that you write, as the following code shows.
When you use MVC, you can indicate how you want a property to be named on a view by using the
DisplayName annotation, as the following lines of code illustrate.
If you have a DateTime property, you can use display and edit data annotations to inform MVC what
format you want the property displayed in.
In the following lines of code, the CreatedDate property is a DateTime and the DisplayFormat data
annotation is used to indicate to MVC that only the day, month, and year values should be displayed.
All the data annotations that are provided with ASP.NET MVC 5 are included in the
System.ComponentModel.DataAnnotations namespace.
Question: In the code on the slide, how can you recognize the display and edit annotations and
distinguish them from other code?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-5
• Email Address. This is required input. The value entered must be a valid email address.
In the following example, when the user submits the form, you want MVC to create a new instance of the
Person model and use it to store the data in the database. However, you want to ensure that the data is
valid before it is stored.
To ensure that the data is valid, you can define the Person model class by using the following lines of
code.
[Required]
public string Name { get; set; }
[Range(0, 400)]
public int Height { get; set; }
[Required]
[RegularExpression(".+\\@.+\\..+")]
public string EmailAddress { get; set; }
}
The Required, Range, StringLength, and RegularExpression annotations implement input validation in
MVC. If users do not enter data that satisfies the criteria specified for each property, the view displays a
standard error message that prompts the user to enter the correct data. In the earlier example, you can
see that the user must enter a Name and a Height between 0 and 400. For the EmailAddress property,
the user must enter a value that matches the regular expression. The regular expression in the example is
a simple expression that requires an @ symbol and a dot.
To specify the error message that the user sees when data is not valid, you can use the ErrorMessage
property on the validation data annotations, as the following code illustrates.
Note: You will see how to ensure that the validation error message is displayed in a view.
Additional Reading: For more examples of validation data annotations see
MCT USE ONLY. STUDENT USE PROHIBITED
03-6 Developing ASP.NET MVC 5 Models
http://go.microsoft.com/fwlink/?LinkID=288950&clcid=0x409
Additional Reading: For more information about the regular expressions that you can use
to check user input, see http://go.microsoft.com/fwlink/?LinkID=288951&clcid=0x409
Question: You want to ensure that users enter a password that is longer than six characters. How should
you do this by using a validation data annotation?
This model binding process can save developers a lot of time and avoid many unexpected run-time errors
that arise from incorrect parameters. MVC includes a default model binder with sophisticated logic that
passes parameters correctly in almost all cases without complex custom code.
• The model class that interests the user. The user has requested a product.
• The operation to perform on the model class. The user has requested that the product be displayed.
• The specific instance of the model class. The user has requested that the product with ID 45 be
displayed.
The request is received by an object called the controller action invoker. The controller action invoker of
the MVC runtime calls a controller action and passes the correct parameters to it. In the example, the
action invoker calls the Display action in the Product controller and passes the ID “45” as a parameter to
the action, so that the right product can be displayed.
The ControllerActionInvoker class is the default action invoker. This action invoker uses model binders
to determine how parameters are passed to actions.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-7
1. The binder examines the definition of the action that it must pass parameters to. In the example, the
binder determines that the action requires an integer parameter called PhotoID.
2. The binder searches for values in the request that can be passed as parameters. In the example, the
binder searches for integers because the action requires an integer. The binder searches for values in
the following locations, in order:
a. Form Values. If the user fills out a form and clicks a submit button, you can find parameters in the
Request.Form collection.
b. Route Values. Depending on the routes that you have defined in your web application, the model
binder may be able to identify parameters in the URL. In the example URL, “45” is identified as a
parameter by the default MVC route.
c. Query Strings. If the user request includes named parameters after a question mark, you can find
these parameters in the Request.QueryString collection.
d. Files. If the user request includes uploaded files, these can be used as parameters.
Notice that if there are form values and route values in the request, form values take precedence. Query
string values are only used if there are no form values and no route values available as parameters.
Model Extensibility
The MVC architecture has been designed to
provide extensibility so that developers can adapt
the architecture to unusual or unique
requirements. For example, the default action
invoker, ControllerActionInvoker, can be
replaced by your own action invoker if you want
to implement your own invoking logic.
Two ways in which you can extend the MVC
handling of MVC models are to create custom
data annotations and custom model binders.
• Running a Data Store Check. You want to check the data entered against data that has already been
stored in the database or in another database store.
• Mathematical Checks. You want to calculate a value from the entered data and check that value is
valid.
In such situations you can create a custom validation data annotation. To do this, you create a class that
inherits from the System.ComponentModel.DataAnnotations.ValidationAttribute class.
The following lines of code illustrate how to create a custom validation data annotation.
MCT USE ONLY. STUDENT USE PROHIBITED
03-8 Developing ASP.NET MVC 5 Models
//Constructor
public LargerThanValidationAttribute (int minimum)
{
MinimumValue = minimum;
}
After you have created a custom validation data attribute, you can use it to annotate a property in your
model, as the following lines of code illustrate.
The following lines of code show how to create a simple custom model binder to pass parameters from
the form collection by implementing the IModelBinder interface.
newCar.brand = brand;
The code example assumes that you have a model class in your MVC application called, Car. It also
assumes that any request for a Car object includes values for color and brand in the form collection. This
situation can easily be handled by the default model binder. However, this example demonstrates how
model binders can locate values from the context of the request and pass those values to the right
properties in the model. You can add custom code to implement extra functionality.
Question: You want to ensure that when a user types a value into the Car Model Number box when
adding a new car to the website, the text entered is not already used by another car in the database.
Would you use a custom validation data annotation or a custom model binder for this?
Demonstration Steps
You will find the steps in the section “Lesson 1: Creating MVC Models“ on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD03_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
03-10 Developing ASP.NET MVC 5 Models
Lesson 2
Working with Data
All web applications present information and almost all web applications require a data store for that
information. By rendering webpages by using data from a data store, you can create a web application
that changes continually in response to user input, administrative actions, and publishing events. The data
store is usually a database, but other data stores are occasionally used. In MVC applications, you can
create a model that implements data access logic and business logic. Alternatively, you can separate
business logic, in model classes, from data access logic, in a repository. A repository is a class that a
controller can call to read and write data from and to a data store. The .NET Framework includes the
Entity Framework and LINQ technologies, which make data access code very quick to write and simple to
understand. In addition, you will see how to build a database-driven website in MVC.
Lesson Objectives
After completing this lesson, you will be able to:
• Connect an application to a database to access and store data.
Connecting to a Database
Most websites use a database to store dynamic
data. By including this data in rendered HTML
pages, you can create a dynamic web application
with content that changes frequently. For
example, you can provide administrative
webpages that enable company employees to
update the product catalog and publish news
items. Products and items are stored in the
database. As soon as they are stored, users can
view and read them. The employees do not need
to edit HTML or republish the website to make
their changes visible.
Some websites may store data in other locations, such as a directory service, but databases are the most
widely used data store.
• Microsoft SQL Server. This is an industry-leading database server from Microsoft. ADO.NET includes
the SqlClient provider for all SQL Server databases.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-11
• Microsoft SQL Server Express. This is a free version of SQL Server that includes a wide range of
database functionality and is very flexible. Some advanced capabilities are not possible with SQL
Express. The SqlClient provider is used for SQL Express.
• OLE DB. This is a standard that many different databases adhere to. ADO.NET includes the OleDb
provider for all OLE DB databases.
• ODBC. This is another older standard that many different databases adhere to. ADO.NET includes the
Odbc provider for all ODBC databases. In general, you should use an OLE DB provider, if it is
available, instead of an ODBC provider.
You can also use third-party ADO.NET providers to access other databases.
Cloud Databases
The database of a web application is usually located on the same server as the web application itself or on
a dedicated database server at the same physical site. However, if you have a fast, reliable Internet
connection, you can consider using a cloud database. Furthermore, if you have chosen to host a web
application in the cloud, a cloud database is a logical storage solution. The Microsoft cloud database
service is called SQL Database and is a part of Microsoft Azure.
Microsoft Azure SQL Database has the following advantages:
• Databases run in Microsoft data centers with the best connectivity and reliability.
• You pay only for the data that you use and distribute.
You can use Microsoft Azure SQL Database with ADO.NET by using the SqlClient provider.
• Add a connection string to the Web.config file. This string specifies the provider, the location of the
database, the security properties, and other properties depending on the provider.
The following markup shows how to add a connection string to Web.config to connect to a SQL Express
database called, PhotoSharingDB, by using the credentials that the web application runs under.
connectionString="Server=tcp:example.database.windows.net,1433;Database=PhotoSharingDB;"
+
"User ID=Admin@example;Password=Pa$$w0rd;Trusted_Connection=False;" +
"Encrypt=True;Connection Timeout=30;PersistSecurityInfo=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
The <connectionStrings> tag must appear within the <configuration> tag, after the
<configSections> tag.
• Code First. You can use the code-first workflow if you prefer to create a model by writing .NET
Framework classes. In this workflow, there is no model file. Instead, you create model classes in C# or
Visual Basic. When you run the application, if the database doesn’t exist, Entity Framework creates the
database.
Framework DbContext class. You will use this class in controllers when you want to manipulate data in
the database. Within this class, add a DbSet<> property for each database table you want Entity
Framework to create in the new database.
The following code shows how to add an Entity Framework context to your model.
In the earlier example, Entity Framework looks for a connection string with the name, PhotoSharingDB,
to match the name of the DbContext class. Entity Framework creates the database at the location that
the connection string provides, and creates two tables in the new database:
• Photos: This table will have columns that match the properties of the Photo model class.
• Comments: This table will have columns that match the properties of the Comment model class.
Question: You have a Microsoft Visio diagram, which a business analyst created that shows all the model
classes for your web application and their relationships. You want to re-create this diagram in Visual
Studio. Which Entity Framework workflow should you use?
//This action gets a photo with a particular ID and passes it to the Details view
public ActionResult Details(int id = 0)
{
Photo photo = db.Photos.Find(id);
if (photo == null)
{
return HttpNotFound();
}
MCT USE ONLY. STUDENT USE PROHIBITED
03-14 Developing ASP.NET MVC 5 Models
You can use an initializer class to populate the database with sample data. This technique ensures that
there is sample data to work with, during development.
The following lines of code show how to create an initializer class that adds two Photo objects to the
Photos table in the database.
After you have created an initializer, you need to ensure that it runs by adding a line of code to the
Global.asax file in the Application_Start method, as the following example illustrates.
Question: You have created an Entity Framework context class in your model, added an initialize, and
called Database.SetInitializer() from Global.asax. When you run the application, no database is created
and no model objects displayed on the webpages. What have you forgotten to do?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-15
if (number == 0)
{
//If a number of photos is not specified, we’ll get all the photos in the database
//This example is in method syntax.
photos = context.Photos.ToList();
}
else
{
//The number specifies how many of the most recent photos the user requests
//Use a LINQ query with both query and method syntax to get these from the database
photos = (from p in context.Photos
orderby p.CreatedDate descending
select p).Take(number).ToList();
}
Demonstration Steps
You will find the steps in the section “Lesson 2: Working with Data“ on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD03_DEMO.md.
1. Define an interface for the repository class. This interface declares the methods that the repository
class uses to read and write data from and to the database.
2. Create and write code for the repository class. This class must implement all the data access methods
declared in the interface.
3. Remove all data access code from the model class.
4. Modify the controller class to use the repository class. Instead, create an instance of the repository
class and call its methods to create the model.
The Comment model class helps users to comment on a photo, as the following lines of code illustrate.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-17
This interface for a comment repository class defines just one method to get the comments for a given
photo, as the following lines of code illustrate.
The CommentRepository class implements the GetComments method as the following lines of code
illustrate.
The CommentsController class uses the repository class, instead of calling Entity Framework methods, as
the following lines of code illustrate.
Note: By using the ICommentRepository interface, the code makes it easy to replace
CommentRespository with another implementation if you need to. However, the
CommentController code still creates a CommentRespository object. You have to modify the
object to make the replacement.
In an even better architecture, you can replace CommentRepository with a different
implementation of ICommentRepository without any changes to the CommentController
class. This is an extremely flexible and adaptable approach and is called a loosely coupled
architecture.
Loosely coupled architectures are also essential for unit testing. You will see how to create a
loosely coupled architecture in Module 6 “Testing and Debugging ASP.NET MVC 5 Web
Applications”.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-19
Objectives
After completing this lab, you will be able to:
• Use display and edit data annotations in the MVC model to assign property attributes to views and
controllers.
• Use Visual Studio to create a new Microsoft Azure SQL database and connect to the database.
• Add Entity Framework code to the model classes in the MVC model.
• Use display and edit data annotations in the MVC model to assign property attributes to views and
controllers.
Lab Setup
Estimated Time: 60 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD03_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD03_LAK.md.
• Add data annotations to the properties to help MVC web application render them in views and
validate user input.
• Add Entity Framework code to the Photo Sharing application in code-first mode.
Question: You are building a site that collects information from customers for their
accounts. You want to ensure that customers enter a valid email address in the Email
property. How would you do this?
Question: You have been asked to create an intranet site that publishes a customer
database, created by the sales department, to all employees within your company. How
would you create the model with Entity Framework?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 03-21
Review Question
Question: At the end of the first iteration of your project, you have a website that displays
photos that users upload. However, during development, the database is empty and users
must upload several photos to the site so they can test the functionality. Your manager wants
you find some way to populate the database whenever it is deployed to the test server. How
can you do this?
Best Practices
• If you want to create a new database for a web application and prefer to write code that describes
your model, use Entity Framework in the code-first workflow to create your model and its classes.
• If you want to separate business logic from data access logic, create separate model classes and
repository classes.
Module 4
Developing ASP.NET MVC 5 Controllers
Contents:
Module Overview 04-1
Module Overview
MVC controllers respond to browser requests, create model objects, and pass them to views for rendering
and displaying in the web browser. If required, controllers can also perform other actions, such as saving
model class changes to the database. Controllers are central to MVC applications. You need to understand
the functioning of controllers to be able to create the right model objects, manipulate them, and pass
them to the right views.
To maximize the re-use of code in controllers, you must know how to program action filters. You can use
action filters to run code before or after every action in your web application, on every action in a
controller, or on other combinations of controller actions.
Objectives
After completing this module, you will be able to:
• Add a controller to a web application that responds to user actions specified in the project design.
• Write code in action filters that runs before or after a controller action.
MCT USE ONLY. STUDENT USE PROHIBITED
04-2 Developing ASP.NET MVC 5 Controllers
Lesson 1
Writing Controllers and Actions
A controller is a .NET Framework class that inherits from the System.Web.Mvc.Controller base class.
Controllers respond to user requests. Within a controller class, you create actions to respond to user
requests. Actions are methods within a controller that return an ActionResult object. The ActionResult
object is often a view that displays a response to the user request; however, it can also yield other types of
results. To process incoming user requests, manage user input and interactions, and implement relevant
application logic, you need to know how to create controllers and actions. You must also know how to
create parameters in action code blocks and pass objects to actions.
Lesson Objectives
After completing this lesson, you will be able to:
• Explain how to use parameters passed in a browser request to a controller action and use them to
change the action result.
• Explain how to pass information to views that have model classes.
2. The controller factory creates a Controller object, and the MvcHandler calls the Execute method in
that controller.
3. The ControllerActionInvoker examines the RequestContext object and determines the action to
call in the Controller object.
4. The ControllerActionInvoker uses a model binder to determine the values to be passed to the
action as parameters.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 04-3
5. The ControllerActionInvoker runs the action. Often, the action creates a new instance of a model
class, perhaps by querying the database with the parameters that the invoker passed to it. This model
object is passed to a view, to display results to the user. Action methods can do many other things
such as rendering views and partial views, redirecting to other websites, displaying snippets of
content, or displaying other files.
Note: The routing engine determines which controller and action receives a request.
Routing is not covered in this section.
Note: You can modify the preceding logic in several ways. For example, you can create
routes that interpret the preceding URLs differently. The examples are true when only the default
route exists.
Let us consider that a user requests a controller called photo, by typing the URL in the Address bar of a
web browser. By default, the MVC DefaultControllerFactory, names this controller class as
PhotoController. You should keep to this convention when you create and name controllers. Otherwise,
you will receive unexpected 404 errors and controllers will not work as intended. If you create a custom
controller factory, you can define your own naming convention for controller classes.
The Microsoft Visual Studio project templates include a folder named Controllers. This is a good location
to create your controllers. Microsoft Visual Studio places controllers in the projectname.Controllers
namespace, by default.
The following example shows the code in an MVC controller class called, PhotoController. The controller
has a single action called Index, which returns a list of Photo items from the Entity Framework context.
Question: What is the convention that you should follow while creating controllers?
Controller actions are public methods that return an ActionResult object. Alternatively, actions can return
objects of many other classes that derive from the ActionResult class. For example, you can write code
for a controller with an Index action to obtain all Photo objects and pass them to the Index view.
When you want to display a specific model object, you must obtain the correct instance from the
database. The following code shows how to display the first Photo object.
A Details Action
public ActionResult First ()
{
Photo firstPhoto = context.Photos.ToList()[0];
if (firstPhoto != null)
{
return View("Details", firstPhoto);
}
else
{
return HttpNotFound();
}
}
Some user actions are in two parts. For example, to create a new Photo, a user can make an HTTP
GET request to the following URL: http://www.adventure-works.com/photo/create.
The following code shows an action that responds to a GET request, to display a new photo form.
{
Photo newPhoto = new Photo();
return View("Create", newPhoto)
}
The Create view displays a form where users can fill photo details, such as the title, description, and so on.
When a user clicks the Submit button, the web browser makes an HTTP POST request.
The following action method responds to a POST request. Note that the method name is the same, but
the [HttpPost] annotation is used to specify that this action responds to the HTTP POST verb.
Note that the ModelState.IsValid property is used to check whether the user has submitted valid data.
You can specify data validation by using validation data annotations in the model class. If the data is valid,
the model object is added and saved. Otherwise, the application displays the Create view again, so that
the user can correct the invalid data.
Note: For the preceding code to work, the Create view must contain a form that uses the
POST method.
Controller actions usually return a view and pass a model class to it, for display. You can create an action
that calls the View() helper, and creates and returns a ViewResult object. The View() helper is available
when you derive from the base Controller class.
Alternatively, you can return an HTTP error. For example, you can create an action such that if a Photo
object is not found, the code creates a 404 not found error by using the HttpNotFound() helper.
Sometimes, you may want to return a file from an action method. For example, let us consider that in a
Photo model, the image file is stored as a byte array in the database. To display this byte array as an
image on a webpage, the action must return it as a .jpeg file, which can be used for the src attribute of an
<img> HTML tag. To return files, you can use the File() helper to return a FileContentResult object. You
can use this technique in the GetImage action.
Other possible action results include:
• PartialViewResult. You can use this action to generate a section of an HTML page, but not a complete
HTML page. Partial views can be re-used in many views throughout a web application.
MCT USE ONLY. STUDENT USE PROHIBITED
04-6 Developing ASP.NET MVC 5 Controllers
• RedirectToRouteResult. You can use this action result to redirect the web browser to another action
method or another route.
• RedirectResult. You can use this action result to redirect to a specific URL, either inside your web
application or to an external location.
• ContentResult. You can use this action result to return text to the web browser. You can return plain
text, XML, a comma-separated table, or other text formats. This text can be rendered in the web
browser or parsed with client-side code.
Child Actions
When an action returns a complete view, MVC sends a new complete webpage to the web browser for
display. Sometimes, you may want to call an action from within a view, to return a piece of content for
display within a webpage. A child action is an action method that can return a small piece of content in
this manner. The FileContentResult is often a good example of a child action, because the image
returned usually forms part of a webpage. Partial views also support child actions.
To declare an action method as a child action, you can use the [ChildActionOnly] annotation. This
annotation ensures that the action method can be called only from within a view by using the
Html.Action() helper. Using this method, you can prevent a user from calling the child action directly by
typing the correct URL into the Address bar.
Question: What are the various ActionResult return types that you can write as code while creating a
controller?
Using Parameters
When users request webpages, they often specify
information other than the name of the webpage
itself. For example, when they request a product
details page, they may specify the name or
catalog number of the product to display. Such
extra information is referred to as parameters. You
must understand how to determine in code what
parameters the user sent in their request.
The following example code shows how to determine the value of the title parameter in a controller
action.
select p;
if (requestedPhoto != null)
{
return View("Details", requestedPhoto);
}
else
{
return HttpNotFound();
}
}
Note that the action method code uses the parameter title to formulate a LINQ to Entities query. In this
case, the query searches for a Photo with the specified Title. Parameters in action methods are frequently
used in this manner.
Note: The example works if the DefaultModelBinder passes parameters. If you create a
custom model binder in your application, you must ensure that it passes parameters in the
correct manner. Otherwise, the action method cannot access the parameters that the user
specified in the request.
To obtain and use the same properties in a view, you can use the following Razor code.
To obtain and use the same values in a view, you can use the following Razor code.
In the examples, note that you can cast any ViewData values other than strings.
Note: At the end of this demonstration, the application will not include views. Therefore,
the application cannot display webpages.
Demonstration Steps
You will find the steps in the “Lesson 1: Writing Controllers and Actions“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD04_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 04-9
When the MVC web application starts, DefaultControllerFactory creates a list of all the classes in the
application that satisfy these criteria. This list helps to create the correct controller rapidly. To write a
controller, you must ensure that all the above mentioned criteria are implemented. Usually, you meet the
IController interface criterion by inheriting from the base Controller class.
By default, the DefaultControllerFactory mandates all controller classes to end with the word Controller.
For example, following this convention, for the Photo model class, you would create a controller called
PhotoController.
• To modify the criteria for selecting controllers. The criteria described earlier are suitable for most web
applications, but sometimes, you may want to change them. For example, you may not want to name
controllers with Controller at the end, or you may want to add extra criteria of your own.
• To support direct injection for testing. Direct injection is a programming technique that lets you specify
classes at run time, instead of specifying classes when writing code. This is helpful for unit testing
because you can inject a test class with mock data, instead of real data. The
DefaultControllerFactory class does not support direct injection.
The following code shows how to create a custom controller factory by implementing the
IControllerFactory interface.
{
public IController CreateController (RequestContext requestContext, string
ControllerName)
{
Type targetType = null;
if (ControllerName == "Photo")
{
targetType = typeof(PhotoController);
}
else
{
targetType = typeof(GeneralPurposeController);
}
return targetType == null ? null :
(IController)Activator.CreateInstance(targetType);
}
You register a custom controller factory by using the ControllerBuilder class in the Global.asax file, as
the following lines of code show.
Question: Can you create a controller that does not end with “Controller”?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 04-11
Lesson 2
Writing Action Filters
In some situations, you may need to run code before or after controller actions run. Before a user runs any
action that modifies data, you might want to run the code that checks the details of the user account. If
you add such code to the actions themselves, you will have to duplicate the code in all the actions where
you want the code to run. Action filters provide a convenient way to avoid code duplication. You need to
know how to create and use action filters in your web application, and when to use them.
Lesson Objectives
After completing this lesson, you will be able to:
Filters
Filters are MVC classes that you can use to manage cross-cutting concerns in your web application. You
can apply a filter to a controller action by annotating the action method with the appropriate attribute.
For example, an action annotated with the [Authorize] attribute, can be run only by authenticated users.
You can also apply a filter to every action in a controller by annotating the controller class with the
attribute.
Filter Types
There are several types of filters that you can use in MVC. These filters run at slightly different stages in
the request process.
Question: Which filter type will you use for the following actions?
1. Intercepting an error
2. Modifying a result
3. Authorizing users
4. Inspecting a returned value
The following code shows how an action filter is used to write text to the Visual Studio Output window in
the order in which the IActionFilter and IResultFilter events run. Place this code in a class file within your
web application.
Note: You can also create a custom authorization filter by implementing the
IAuthorizationFilter interface. However, the default AuthorizeAttribute implementation is
highly useful and satisfies almost all authentication requirements. You should be careful when
overriding the default security code in MVC or any other programming model. If you do so
without a full understanding of the implications, you can introduce security vulnerabilities that a
malicious user can exploit.
[SimpleActionFilter]
public ActionResult Index()
{
return View("Index", contextDB.Photos.ToList());
}
}
3. You are writing a photo sharing application and you want to prevent unauthenticated users from
adding comments to a photo.
4. You want to prevent malicious users from intercepting the credentials entered by users in the logon
form for your web application. You want to ensure that the credentials are encrypted.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 04-15
The members of your development team are new to ASP.NET MVC and they find the use of controller
actions confusing. Therefore, you need to help them by adding a component that displays action
parameters in the Visual Studio Output window whenever an action runs. You will add an action filter to
achieve this.
Note: The controllers and views that you have added in the lab of module 3 were to test
your new model classes. They have been removed from the project to create the actual
controllers. You will create temporary views to test these controllers at the end of this lab.
Objectives
After completing this lab, you will be able to:
• Write actions in an MVC controller that respond to user operations such as create, index, display, and
delete.
Lab Setup
Estimated Time: 60 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD04_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD04_LAK.md.
• Index. This action gets a list of all the Photo objects and passes the list to the Index view for display.
• Display. This action takes an ID to find a single Photo object. It passes the Photo to the Display view
for display.
• Create (GET). This action creates a new Photo object and passes it to the Create view, which displays a
form that the visitor can use to upload a photo and describe it.
• Create (POST). This action receives a Photo object from the Create view and saves the details to the
database.
MCT USE ONLY. STUDENT USE PROHIBITED
04-16 Developing ASP.NET MVC 5 Controllers
• Delete (GET). This action displays a Photo object and requests confirmation from the user to delete
the Photo object.
• Create a temporary index and display views by using the scaffold code that is built into the Visual
Studio MVC application template.
• Use the views to test controllers, actions, and action filters, and run the Photo Sharing application.
Question: What happens if you click the Edit or Delete links in the Index view in the Lab?
Question: Why did you use the ActionName annotation for the DeleteConfirmed action in
the PhotoController class?
Question: In the lab, you added two actions with the name, Create. Why is it possible to add
these actions without using the ActionName annotation?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 04-17
Review Question
Question: You want to ensure that the CreatedDate property of a new Photo object is set
to today’s date when the object is created. Should this value be set in the Photo model class
constructor method or in the PhotoController Create action method?
Best Practices
• Unless you have a good reason not to, keep to the convention that each controller should be
named to match the corresponding model class, with “Controller” appended. For example,
for the Photo model class, the controller should be called PhotoController. By maintaining
this convention, you create a logically named set of model and controller classes, and can
use the default controller factory.
• Take great care if you choose to override the built-in AuthorizeAttribute filter because it
implements permissions and security for the web application. If you carelessly modify the
security infrastructure of the MVC framework, you may introduce vulnerabilities in your
application. Instead, use the built-in filter wherever possible.
MCT USE ONLY. STUDENT USE PROHIBITED
04-18 Developing ASP.NET MVC 5 Controllers
MCT USE ONLY. STUDENT USE PROHIBITED
05-1
Module 5
Developing ASP.NET MVC 5 Views
Contents:
Module Overview 05-1
Module Overview
Views are one of the three major components of the MVC programming model. You can construct the
user interface for your web application by writing views. A view is a mixture of HTML markup and code
that runs on the web server. You need to know how to write the HTML and code found in a view and use
the various helper classes built into MVC. You also need to know how to write partial views, which render
sections of HTML that can be re-used in many places in your web application. The knowledge of creating
views will help you develop webpages that present dynamic content.
Objectives
After completing this module, you will be able to:
• Create an MVC view and add Razor markup to it to display data to users.
• Use HTML helpers in a view to render controls, links, and other HTML elements.
Lesson 1
Creating Views with Razor Syntax
When a user makes a request to an MVC web application, a controller responds. Often, the controller
action instantiates a model object, for example, a Product. The controller might get the Product by
querying the database, by creating a new Product, or by performing some other step. To display the
Product, the controller creates a view and passes the Product to it. The view builds a webpage by
inserting properties from the Product, and sometimes, from other sources, into HTML markup. MVC
sends the completed webpage to the browser. To create views, you must understand how MVC interprets
the code you place in views and how a completed HTML page is built. By default, the Razor view engine
performs this interpretation, but you can also use other view engines. If you take time to understand
Razor, you will find it to be an excellent and versatile view engine that gives a great degree of control over
the rendered HTML. Other view engines have very different syntaxes, which you may prefer if you have
worked with earlier versions of ASP.NET or other server-side web technologies, such as Ruby on Rails.
Lesson Objectives
After completing this lesson, you will be able to:
• Add views to an MVC 5 web application.
• Explain how to render HTML that is accessible to visitors with low vision.
Adding Views
In an MVC application, there is usually one
controller for every model class. For example, a
model class named Product usually has a
controller called ProductController that contains
all the actions relevant to products. There may be
some controllers that do not correspond to any
model classes, such as the HomeController.
However, each controller can have multiple views.
For example, you may want to create the
following views for Product objects:
• Create. The create view can enable users to add a new Product in the catalog.
• Edit. The edit view can enable users to modify the properties of an existing Product.
• Delete. The delete view can enable users to remove a Product from the catalog.
• Index. The index view can display all the Product objects in the catalog.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-3
By convention, an MVC web application creates all views within the top-level Views folder. Within this
folder, there is a folder for each controller in the application. In the preceding example, the Views folder
would contain a Product folder. This folder would contain the Details, Create, Edit, Delete, and Index
views.
If you use the Razor view engine and the C# language, views are files with a .cshtml extension. If you use
the Razor view engine and the Visual Basic language, views are files with a .vbhtml extension. Other view
engines use different extensions.
1. In the Solution Explorer pane, select the folder where you want to create the view. For example, for
a controller named ProductController, MVC expects view files to be located in the Views/Product
folder.
2. Right-click the selected folder, point to Add, and then select View.
Alternatively, you can create a view file for a particular controller action by opening the controller code
file, right-clicking the action, and then clicking Add View. If you create a view by using the controller
code file, some properties in the Add View dialog box are filled in by default.
The following table describes the properties that you must complete in the Add View dialog box.
Property Description
View name This is the name of the view. The view file name is this name with the
appropriate extension added. The name you choose should match the
name returned by the corresponding controller action. If the action
controller does not specify the name of the view to use, MVC assumes
the name of the view matches the name of the controller action.
Model class If you create a strongly-typed view, you need to specify the model class
to bind to the view. Visual Studio will use this class when it formulates
IntelliSense prompts and checks for compile-time errors.
Template A template is a basic view that Visual Studio can use to create the view. If
you specify a model class for the view, Visual Studio can create simple
templates for Create, Edit, Details, Delete, and List views. When you
become more experienced in using views, you may prefer to build a view
from the empty scaffold template, rather than use populated scaffold
templates.
Reference script libraries When you select this check box, links to common client-side script files
are included in the view. These links include the jQuery JavaScript library.
Create as a partial view A partial view is a section of Razor code that you can re-use in multiple
views in your application.
Use a layout page A layout page can be used to impose a standard layout and branding on
many pages within the web application.
Question: You are using the Razor view engine and Visual Basic to create views. You right-click the
Delete action in the CustomerController.vb file. What is the name of the view file that Visual Studio will
create by default?
MCT USE ONLY. STUDENT USE PROHIBITED
05-4 Developing ASP.NET MVC 5 Views
<p>
The photo title is:
@Model.Title
</p>
A section of code marked with the @ symbol is referred to as a Razor code expression. In Razor syntax,
you mark the start of a Razor code expression with the @ symbol. Razor lacks an expression ending
symbol. Instead, Razor infers the end of a code expression by using a fairly sophisticated parsing engine.
If you want to declare several lines as content, use the <text> tag instead of the @: delimiter. Razor
removes the <text> and </text> tags before returning the content to the browser.
In the following code example, Razor interprets the @: delimiter to display plain text.
HTML Encoding
For security reasons, when Razor runs any server-side code that returns a string, it encodes the string as
HTML before rendering it to the browser. For example, you may have a Comment model class with the
following properties:
• Subject. This property contains a subject for the comment as a simple string with no formatting
information.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-5
• HtmlComment. This property contains the comment text itself. More important, it includes the
formatting information as HTML tags. For example, it might include <i> tags to italicize a word.
If you have used the normal @Model.HtmlComment syntax to return the formatted comment text,
Razor encodes “<” as “<” and “>” as “>” in the HTML source. This results in the user seeing “<i>” on
the webpage. This is not the behavior you intend because you want the users to see italicized text.
To render text without HTML encoding, use the Html.Raw() helper. For example, use
@Html.Raw(Model.HtmlComment).
Note: Razor encodes text as HTML for a specific security reason—to stop malicious users
from injecting malicious code into your web application. If such attacks are successful, injected
code may circumvent security restrictions in your web application and deny service to users, or it
may access sensitive information. Therefore, you should only use the Html.Raw() helper when it
is absolutely necessary. Also, if you must use the Html.Raw() helper, you must ensure that it does
not operate on unchecked strings entered by users.
Razor Comments
You may want to include comments in your Razor
code to describe it to other developers in your
team. This is an important technique that
improves developer productivity by making it
easier to understand code.
A Razor Comment
@* This text will not be rendered by the Razor view engine, because this is a comment. *@
For example, if the Product.Price property contains the value 2.00, the following code renders “Price
Including Sales Tax: 2.00 * 1.2”.
You can control and alter this behavior by using parentheses to enclose the expression for Razor to
evaluate.
For example, if the Product.Price property contains the value 2.00, the following code renders “Price
Including Sales Tax: 2.40”.
MCT USE ONLY. STUDENT USE PROHIBITED
05-6 Developing ASP.NET MVC 5 Views
Razor also includes code blocks that run conditional statements or loop through collections.
For example, Razor runs the following code only if the Product.InStock Boolean property returns true.
Razor loops are useful for creating index views, which display many objects of a particular model class. A
product catalog page, which displays many products from the database, is a good example of an index
view. To implement an index view, a controller action passes an enumerable collection of objects to the
view.
You can loop through all the objects in an enumerable collection by using the foreach code block:
Question: You want to describe a code block to developers in your view file. You do not want your
description to be passed to the browser. What syntax should you use?
Strongly-Typed Views
In many cases, when you create a view, you know
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-7
that the controller action will always pass an object of a specific model class. For example, if you are
writing the Display view for the Display action in the Product controller, you know from the action code
that the action will always pass a Product object to the view.
In such cases, you can create a strongly-typed view. A strongly-typed view is a view that includes a
declaration of the model class. When you declare the model class in the view, Visual Studio helps you with
additional IntelliSense feedback and error-checking as you write the code. This is possible because Visual
Studio can check the properties that the model class includes. Troubleshooting run-time errors is also
easy. You should create strongly-typed views whenever you can so that you benefit from this extra
IntelliSense and error-checking. If you follow this as a best practice, you will make fewer coding errors. A
strongly-typed view only works with an object of the model class in the declaration.
To create a strongly-typed view in Visual Studio, in the Add View dialog box, choose a model class to
bind to the view.
You can choose the Product model class so that Visual Studio can bind the view to the class you specify,
by adding the following line of code at the top of the view file.
Later in the view file, you can access properties of the model object by using the Model helper. For
example, you might access a product catalog number in this manner: @Model.CatalogNumber.
The following code example shows a multiple-item view with the model declaration and the loop that
enumerates all the Product objects passed by the action.
<h1>Product Catalog</h1>
Furthermore, sometimes, the controller action does not pass any model class to the view. The most
common example of such a classless view is the site home page.
In such cases, you can create a dynamic view. A dynamic view does not include the @model declaration
at the top of the page. You can choose to add the @model declaration to change the view into a
strongly-typed view, later.
MCT USE ONLY. STUDENT USE PROHIBITED
05-8 Developing ASP.NET MVC 5 Views
When you create dynamic views, you receive less helpful IntelliSense feedback and error checking because
Visual Studio cannot check the model class properties to verify the code. In such scenarios, you have to
ensure that you access only the properties that exist. To access a property that may or may not exist, such
as the ThirdPartyProduct.Supplier property in the preceding example, check the property for null
before you use it.
Question: You want to write a view that displays ten objects of the Photo model class. What model
declaration should you use?
Users have different requirements depending on their abilities and disabilities. For example, consider the
following factors:
• Users with low vision may use a standard browser, but they may increase text size with a screen
magnifier so that they can read the content.
• Profoundly blind users may use a browser with text-to-speech software or text-to-Braille hardware.
• Color-blind users may have difficulty if a color difference is used to highlight text.
• Users with limited dexterity may find it difficult to click small targets.
• User with epilepsy may have seizures if presented with flashing content.
You can ensure that your content is accessible to the broadest range of users by adhering to the following
guidelines:
• Do not rely on color differences to highlight text or other content. For example, links should be
underlined or formatted in bold font to emphasize them to color-blind users.
• Always provide equivalent alternative content for visual and auditory content. For example, always
complete the alt attribute for images. Use this attribute to describe the image so that text-to-speech
software or text-to-Braille hardware can render meaningful words to the user.
• Use markup and style sheets to separate content from structure and presentation code. This helps
text interpretation software to render content to users without being confused by structural and
presentation code. For example, you should apply the following best practices to display content on
your webpage:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-9
o Avoid using tables to display the content. You should use tables only to present tabulated
content. Tables can be used to render graphics and branding on a webpage, but in an accessible
site, use positional style sheets to display content. Text readers do not read style sheets.
o Avoid using nested tables. In a nested table, a table cell contains another table. These are
particularly confusing to text readers because they read each table cell in a sequential order. The
user is likely to become disoriented and unable to determine which cell is being read and what it
means.
o Avoid using images that include important text. Text readers cannot render text from within an
image file. Instead, use markup to render this text.
Additional Reading: The World Wide Web Consortium (W3C) has a project called the Web
Accessibility Initiative (WAI) that promotes accessible web content. This project has published the
Web Content Accessibility Guidelines (WCAG). These guidelines are accepted by the web
publishing industry as definitive. To read the full guidelines, go to:
http://go.microsoft.com/fwlink/?LinkID=288955&clcid=0x409
Note: In ASP.NET MVC, the developer has complete control over the HTML that the web
server sends to the web browser. However, you must understand accessibility principles to write
accessible MVC views. Ensure that your entire development team is familiar with the
requirements of accessibility and the related best practices.
Question: You want to present your company logo at the uppermost part of the page. The logo is a .gif
file that includes the name of the company in an unusual font. How can you ensure that the logo is
accessible?
MCT USE ONLY. STUDENT USE PROHIBITED
05-10 Developing ASP.NET MVC 5 Views
Lesson 2
Using HTML Helpers
The ASP.NET MVC 5 Framework includes many HTML helper functions that you can use in views. HTML
helpers are C# methods that you can call to render values, labels, and input controls such as text boxes.
Helpers include common logic that makes it easier for you to render HTML for MVC model class
properties and other tasks. Some HTML helpers examine the definition of a property in a model class and
then render appropriate HTML. Some HTML helpers call controller actions and others validate user input
data. You can also create custom HTML helpers. You need to know the appropriate HTML helper to use in
any scenario and how to pass the correct parameters to relevant HTML helpers.
Lesson Objectives
After completing this lesson, you will be able to:
• Use the Html.LabelFor and HTML.EditorFor helpers to render an editor control for a model class
property.
• Use the Html.BeginForm helper to render a form for a controller action.
• Use various HTML helpers to build a user interface for a web application.
In the following code example, the Html.Actionlink() helper renders an <a> element that calls the
Display action in the Photo controller, and passes an integer for the photo ID.
Notice that you pass parameters to the helper by using an anonymous object. In this manner, you can
pass multiple parameters.
Note: The Html.ActionLink() helper works with the routing engine to formulate the
correct URL for the link. The helper will render the href value above, assuming it is called from a
PhotoController view. There are several overloads of the ActionLink helper, however, if you wish
to use it to call actions in other controllers.
You can use the Url.Action() helper to populate the src attribute of an <img> element or <script>
element. This helper is useful whenever you want to formulate a URL to a controller action without
rendering a hyperlink.
The following code example shows how to render an image by calling the Url.Action helper within the
src attribute of an img element:
Additional Reading: For more information about the Html.ActionLink() and Url.Action()
helpers, see:
http://go.microsoft.com/fwlink/?LinkID=288959&clcid=0x409
http://go.microsoft.com/fwlink/?LinkID=288960&clcid=0x409
Question: You want to render an HTML5 <audio> tag to play a sound file from an action. Would you use
the Html.ActionLink() helper or the Url.Action() helper?
MCT USE ONLY. STUDENT USE PROHIBITED
05-12 Developing ASP.NET MVC 5 Views
The following code example renders the display name of the CreatedDate property by using the
Html.DisplayNameFor() HTML helper.
The text rendered by the Html.DisplayNameFor() helper depends on the model class. If you used a
DisplayName annotation to give a more descriptive name to a property, then Html.DisplayNameFor()
will use that DisplayName annotation value; otherwise, it will render the name of the property.
If you used the DisplayFormat annotation in the model class with DataFormatString set to
“{0:dd/MM/yy}”, then the Html.DisplayFor() helper ensures that the date is displayed in short date
format.
Question: You want to ensure that a view displays “This product was last changed on” before the
ModifiedDate property. This text is declared in the class with the DisplayName annotation. What code
would you write in the view?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-13
You can also specify the HTTP method that the form uses to submit data. If the form uses the POST
method, which is the default, the browser sends form values to the web server in the body of the form. If
the form uses the GET method, the browser sends form values to the web server in the query string in the
URL.
In the rendered HTML, the <form> element must be closed with a </form> tag. In Razor views, you can
ensure that the form element is closed with an @using code block. Razor renders the </form> tag at the
closing bracket of the code block.
The following code example shows how to render a form that sends data to the Register action in the
CustomerController. The form uses the POST HTTP verb.
You can specify additional attributes for the <form> element by passing them in an htmlAttributes
parameter as new objects. This is a good method to use to add the enctype attribute. If the form includes
any uploaded files, you must set the enctype attribute to multipart/form-data.
The following code example shows how to render a file upload form that sends data to the Create action
in the ProductController. The form uses the POST verb and sets the enctype attribute.
Question: You have created a form with a file selector control that uses the GET method. You have set the
enctype attribute to multipart/form-data, but when you try to access the file in the action method, an
exception is thrown. What have you possibly done incorrectly?
Text box <input type="text" A single-line text box in which the user can enter a
name="Title"> string. The name attribute is used to identify the
entered value in the query string or to send form data
by using the POST method.
Multi-line <textarea A multi-line text box in which the user can enter
text box name="Description" longer strings.
rows="20" cols="80">
name="ContactMe">
Please send me new
offer details
Additional Reading: For more information about all HTML form elements, go to:
http://go.microsoft.com/fwlink/?LinkID=288961&clcid=0x409
The following code example renders a label for the CreatedDate property.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-15
If the action passes an existing model object to the view, the Html.EditorFor() helper also populates each
control with the current values of each property.
The following code example renders a check box for the ContactMe property.
Question: You have a property in the Product model class named ProductID. You want to include this in
the HTML page so that client-side script can use the ProductID value. However, you do not want the
value to be displayed to users. In the model class, you have annotated the ProductID property with the
[HiddenInput(DisplayValue=false)] attribute. How will the Html.EditorFor() helper render this
property?
MCT USE ONLY. STUDENT USE PROHIBITED
05-16 Developing ASP.NET MVC 5 Views
Demonstration Steps
You will find the steps in the “Lesson 2: Using HTML Helpers“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD05_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
05-18 Developing ASP.NET MVC 5 Views
Lesson 3
Re-using Code in Views
In a web application, you frequently render similar blocks of HTML content in different webpages. For
example, in an e-commerce web application, you might want to display the most popular products on the
home page, on the front page of the product catalog, at the top of the product search page, and perhaps
in other locations. To render such HTML content in an MVC application, you may copy and paste code
from one Razor view into others. However, to change the display of top products later in the project, you
would then have to make identical changes in many locations. A better practice is to use a partial view. A
partial view renders a section of HTML content that can be inserted into several other views at run time.
Because the partial view is a single file that is re-used in several locations, when you implement a change
in a single location, the changes are updated in other locations in the web application. Partial views
increase the manageability of MVC web applications and facilitate a consistent presentation of content
throughout a web application.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe how partial views enable you to re-use Razor code.
• Next, create a controller action that retrieves the most popular comments, and then passes them to
the partial view.
• Then, create another controller action that uses the article ID to find comments specific to that article.
The controller action then passes this collection of comments to the partial view.
• Finally, call the appropriate actions from the home page and the article view.
Because the partial view renders a collection of comments, you can re-use it for various situations by
passing different collections to it from controller actions.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-19
Partial views are often created inside the /Views/Shared folder in your site. Views in the Shared folder
are accessible to many controllers, whereas views in the /Views/Comment folder are accessible only from
the CommentController.
In the following example of a partial view, you can see the @model declaration that makes the partial
view strongly-typed. You can also see that the partial view renders only an unordered list and not a
complete HTML webpage as the following lines of code indicate.
<ul>
@foreach (var item in Model) {
<li>
Subject: @Html.DisplayFor(modelItem => item.Subject)
</li>
}
</ul>
Question: You want to create a partial view that displays a list of comments. The comments partial view
will be called by actions in the PhotoController and the HomeController. In which folder should you
create the partial view file?
second optional parameter is a model object for the partial view to render. This is the same model object
that the parent view uses because other model objects are not available in this context.
The following lines of code call the _Comments.cshtml partial view without passing a model object.
Remember that you can use the ViewBag and ViewData collections to pass data between the action
method and the view. A parent view will share the same ViewBag or ViewData objects with the partial
view. This is a good way to share data between the controller action, view, and partial view.
Consider an Article view that displays the text and title of an Article object. You want to display
comments at the end of this view in a partial view. You can use the Html.Action() helper to call an action
in the Comments controller that returns such a partial view. The partial view can work with a collection of
Comment objects.
In the following example, the Html.Action() helper calls an action in the CommentController controller
and passes the ID of the current article model object.
Question: You want to display user reviews of a product to each product page. You have created a
_ReviewsForProduct partial view. Would you use Html.Partial() or Html.Action() to render this view?
• You have a photo sharing web application and you want to display a gallery of thumbnail images on
both the AllPhotos view and the home page Index view. The AllPhotos view should show every
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-21
Photo object, but the home page Index view should display only the three most recent photos
uploaded.
• If you decide to create a partial view, whether you need to use the Html.Partial() or the
Html.Action() HTML helper in the parent view.
MCT USE ONLY. STUDENT USE PROHIBITED
05-22 Developing ASP.NET MVC 5 Views
• A Display view for the Photo model objects. This view will display a single photo in a large size, with
the title, description, owner, and created date properties.
• A Create view for the Photo model objects. This view will enable users to upload a new photo to the
gallery and set the title and description properties.
• A Photo Gallery partial view. This view will display many photos in thumbnail sizes, with the title,
owner, and created date properties. This view will be used on the All Photos webpage to display all
the photos in the application. In addition, this view will also be used on the home page to display the
three most recent photos.
After adding these three views to the photo sharing application, you will also test the working of the web
application.
Objectives
After completing this lab, you will be able to:
• Add Razor views to an MVC application and set properties such as scaffold and model binding.
• Write both HTML markup and C# code in a view by using Razor syntax.
Lab Setup
Estimated Time: 50 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD05_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD05_LAK.md.
• Display the properties of a photo such as title, description, and created date.
• Display the properties of a photo, such as title, description, and created date.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 05-23
Question: In the lab, how did you ensure that the Create view for Photo model objects
could upload photo files when the user clicked the Create button?
MCT USE ONLY. STUDENT USE PROHIBITED
05-24 Developing ASP.NET MVC 5 Views
Review Questions
Question: You want to display the name of the Comment.Subject property in an MVC view
that renders an Edit form for comments. You want the label Edit Subject to appear to the left
of a text box so that a user can edit the Subject value. Which HTML helper should you use to
render the field name?
Question: Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
Best Practices
• Use Razor comments, declared with the @* *@ delimiters, throughout your Razor views to
help explain the view code to other developers in your team.
• Only use @: and <text> tags when Razor misinterprets content as code. Razor has
sophisticated logic for distinguishing content from code, so this is rarely necessary.
• Use strongly-typed views wherever possible because Visual Studio helps you to write correct
code by displaying IntelliSense feedback.
Module 6
Testing and Debugging ASP.NET MVC 5 Web Applications
Contents:
Module Overview 06-1
Module Overview
Software systems such as web applications are complex and require multiple components, often written
by different developers, to work together. Incorrect assumptions, inaccurate understanding, coding errors,
and many other sources can create bugs that result in exceptions or unexpected behavior. To improve the
quality of your web application and create a satisfying user experience, you must identify bugs from any
source and eliminate them. Traditionally, most testing has been performed at the end of a development
project. However, it has recently become widely accepted that testing throughout the project life cycle
improves quality and ensures that there are no bugs in production software. You need to understand how
to run tests on small components of your web application to ensure that they function as expected before
you assemble them into a complete web application. You also need to know how to use the tools
available in Microsoft Visual Studio 2017 to debug and trace exceptions when they arise.
Objectives
After completing this module, you will be able to:
• Run unit tests against the Model–View–Controller (MVC) components, such as model classes, and
locate potential bugs.
Lesson 1
Unit Testing MVC Components
A unit test is a procedure that instantiates a component that you have written, calls one aspect of the
functionalities of the component, and checks that the component responds correctly according to the
design. In object-oriented programming, unit tests usually instantiate a class and call one of its methods.
In an MVC web application, unit tests can instantiate model classes or controllers and call their methods
and actions. As a web developer, you need to know how to create a testing project and add tests to the
testing project. The tests check individual aspects of your code without relying on database servers,
network connections, and other infrastructure. This is because unit tests focus on the code you write.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the use of unit tests to improve the quality of code you write.
• Describe how loosely-coupled components increase the testability and maintainability of your
application.
• Write unit tests against model classes, controllers, and views in an MVC web application.
• Describe how Inversion of Control (IoC) containers can instantiate controllers and model classes.
• Run unit tests in Visual Studio 2017.
• Acceptance Tests: Acceptance tests focus on a functional or technical requirement that must work for
the stakeholders to accept the application. Similar to integration tests, acceptance tests usually test
multiple components working together.
Note: Unit tests are important because they can be defined early in development.
Integration and acceptance tests are usually run later, when several components are approaching
completion.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 06-3
A single unit test usually consists of code that runs in three phases:
1. Arrange. In this phase, the test creates an instance of the class that it will test. It also assigns any
required properties and creates any required objects to complete the test. Only properties and
objects that are essential to the test are created.
2. Act. In this phase, the test runs the functionality that it must check. Usually, in the Act phase, the test
calls a single procedure and stores the result in a variable.
3. Assert. In this phase, the test checks the result against the expected result. If the result matches what
was expected, the test passes. Otherwise, the test fails.
This is important because new code can cause bugs at any stage of the development process. As an
example, consider a project that proceeds through three phases. A unit test defined for phase 1 helps
highlight problems in phases 2 and 3 that might otherwise go unnoticed:
1. Phase 1. The ProductController class is defined and the Test_Index_Action unit test is written. The
test checks that the Index action works with an integer parameter. When you call the Index action
with an integer, the action returns a collection that includes the same number of Product objects.
The test passes.
2. Phase 2. A developer modifies the Index action so that it returns a partial view. The developer
renames the action _Index to conform to the team’s partial view naming convention. The test fails
because the name has changed. The developer modifies the test so that it calls the renamed action
and the test passes.
3. Phase 3. A developer modifies the Index action by writing a different Language Integrated Query
(LINQ) to implement a new functional requirement. However, the developer makes a mistake in the
LINQ syntax. The Index action now returns zero products regardless of the integer that is passed as a
parameter. The test fails.
MCT USE ONLY. STUDENT USE PROHIBITED
06-4 Testing and Debugging ASP.NET MVC 5 Web Applications
In Phase 2, the test failure arose because the action name had changed, not because of a mistake in the
action code. The solution was to change the name of the action called in the test method, but this can
remind developers to alter calls to renamed actions throughout the solution.
In Phase 3, the test failure arose because the developer misunderstood LINQ or made a typing error in the
LINQ syntax. The unit test highlighted the error as soon as it arose. This helps the developer focus on a
solution to resolve the test failure and ensure that new functionality does not cause failures in code
written earlier in the project.
Question: Board members want you to ensure that your web application correctly calculates sales tax on
every product in the catalog. Is this an example of a unit test, an integration test, or an acceptance test?
1. Write the Test. The developer starts by creating and coding the unit test. This step requires a full
understanding of the functional requirement, which can be obtained from use cases or user stories.
Because the developer has not written any code in the application, the test fails.
2. Pass the Test. The developer writes some quick and simple code in the application so that it passes
the test. During the first iteration, this code is frequently inelegant and may include false assumptions
such as hardcoded values.
3. Refactor. The developer cleans up the application code, removes duplicate code, removes hardcoded
values, improves readability, and makes other technical improvements. The developer reruns the test
to ensure that refactoring has not caused a failure.
The cycle is then repeated. In each iteration, the developer adds a small new element of the final
functionality with a corresponding test.
It is important that the code in your tests is treated as production code. It should be well thought out and
easy to read so that other developers can understand the test and quickly diagnose any test failures.
• Write tests before code. In the TDD development cycle, the test is created in step one before any code
in the application. This means the test must fail the first time it is run. You can understand the test as
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 06-5
a specification for the functionality you are building. By writing the test first, you ensure that you
begin with a thorough understanding of the problem you are trying to solve.
• Move in small steps. By breaking a large application down into small elements of functionality, you
can improve developer productivity. You can do this by giving a developer a small problem to solve
in each iteration. The developer can solve the simple problem quickly and understand all the possible
circumstances in which their code runs.
• Only write enough code to pass the test. In each iteration, do not be tempted to add extra code that is
not related to the test. For example, if you know that users will call an action with other parameters
than the ones in the test, do not write code to handle these parameters. Instead, during the next
iteration, write a second test for those parameters. Then write and refactor that code.
Developers can refer to tests as examples of how to use a class or method. This can increase developer
productivity because developers can view the code that demonstrates the method or class.
Note: In the lab, you will use some TDD principals as you develop the solution. However,
the lab does not conform to a strict reading of the TDD methods.
Question: You have written a controller for the Comment model class. You write a unit test that checks
that the Index action returns a collection of Comment objects. Have you conformed to TDD principles?
You are writing an MVC web application that displays a product catalog and enables users to click a
product to view the full details. On the product details page, users can view and add reviews of that
product. You want to ensure during testing that the Product.Reviews property, which is a collection of
Review objects, only includes reviews with the right ProductID value.
Recall that unit tests should not rely on infrastructure such as network connections or database servers,
but only on test code. By contrast, in production, the application will obtain all product reviews from a
database. To satisfy the needs of testing and production, you can build the following components:
• An IProduct interface. This includes a definition of the Reviews property, together with other
properties and methods. This interface is known as a repository.
• A Product class. This is the implementation of the IProduct repository that the application uses in
production. When the user calls the Reviews property, all the reviews for the current product are
obtained from the database.
• A TestProduct class. This is the test double or fake implementation of the IProduct repository that
the test uses. The test sets up a TestProduct object and fake reviews with different ProductID values.
The test calls the TestProduct.Reviews property and checks that only the right reviews are returned.
Notice that, in the test, the TestProduct double uses in-memory data set up during the Arrange phase. It
does not query the database. Therefore, you can test your code without relying on the network
connection to the database or the database server itself. This approach also ensures that the test runs
quickly, which is important because slow tests discourage developers from running tests regularly.
Question: In a test, you create a fake collection of BlogEntry objects. Is this an example of an interface or
a test double?
In a Visual Studio test project, test fixtures are classes marked with the [TestClass] annotation. Unit tests
are methods marked with the [TestMethod] annotation. Unit tests usually return void but call a method
of the Assert class, such as Assert.AreEqual() to check results in the test Assert phase.
Note: There are many other test frameworks available for MVC web applications and you
can choose the one you prefer. Many of these frameworks can be added by using the NuGet
package manager available in Visual Studio.
In the following code example, the IWebStoreContext interface is a repository that defines methods such
as Add() and Delete(), and properties such as Products.
A Repository Interface
public interface IWebStoreContext
{
IQueryable<Product> Products { get; }
T Add<T>(T entity) where T : class;
Product FindProductById(int ID);
T Delete<T>(T entity) where T : class;
}
MCT USE ONLY. STUDENT USE PROHIBITED
06-8 Testing and Debugging ASP.NET MVC 5 Web Applications
• An implementation of the repository for use in production and development. This implementation
will use data from the database or some other storage mechanism.
• An implementation of the repository for use in tests. This implementation will use data from the
memory set during the Arrange phase of each test.
The following code example shows how to implement the repository interface in your MVC project for use
in production and development.
T IWebStoreContext.Add<T>(T entity)
{
return Set<T>().Add(entity);
}
T IWebStoreContext.Delete<T>(T entity)
{
return Set<T>().Remove(entity);
}
}
Note that the WebStoreContext class still inherits from the Entity Framework DbContext class but also
implements the IWebStoreContext interface that you just created. In fact, the interface methods such as
Add(), Delete(), and FindProductById() just wrap methods from the DbContext class such as
Remove().
The following code example shows how to implement a repository class for tests.
The following code example shows how to test a controller action by using a test double for the Entity
Framework context.
Assert.AreEqual(typeof(List<Product>), result.Model.GetType());
}
Note that the test creates a new instance of the FakeWebStoreContext class and adds three Product
objects to it. In this case, you can run the test without setting any properties on the Product objects. This
context is passed to the ProductController constructor and the test proceeds to the Act and Assert
phases.
Question: For what purpose would you use a fake repository when you write unit tests against an MVC
controller?
Scenario Context
In unit tests In a unit test, you should test code without relying on underlying infrastructure
such as databases. You can use a test double class that behaves like an Entity
Framework context, but uses in-memory data.
At other times When you are not unit testing the code, you use an actual Entity Framework
context in your controller code, which interacts with a database.
//The parameterless version of the constructor is used by the MVC controller factory
public ProductController()
{
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 06-11
//This constructor is used by unit tests. They pass a test double context
public ProductController(IWebStoreContext Context)
{
//Use the context passed to the constructor
context = Context;
}
Note: IoC frameworks are also known as Dependency Injection (DI) frameworks because
they inject classes that implement the correct interfaces into class constructors.
By using an IoC container, you avoid the need to create two constructors for controller classes. During
tests, you can instantiate the test double and pass it to the controller constructor. At other times, the IoC
container instantiates the actual Entity Framework context and passes it to the controller constructor.
Note: There are many IoC containers designed for use with ASP.NET MVC web applications.
These replace certain components of the MVC framework to support IoC. For example, they
replace the default controller factory with a factory that instantiates controllers with the right
context class. Many IoC containers are available in the NuGet package library, such as NinJect
and StructureMap.
Question: Which approach is more loosely-coupled: using constructors to specify the context, or using
IoC containers to specify the context?
Demonstration Steps
You will find the steps in the “Lesson 1: Unit Testing MVC Components“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD06_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
06-12 Testing and Debugging ASP.NET MVC 5 Web Applications
Note: Mocking frameworks for ASP.NET MVC 5 include Moq and NSubstitute. These
frameworks are available in NuGet and there are alternatives. Choose the framework that best
suits your testing needs.
• Creating multiple mock objects of a single type. You should try to keep each unit test as simple as
possible, but inevitably, some tests require many mock objects to work with. For example, if you are
testing a method that underlies paging functionality in your web application, you must create
enough mock objects to populate multiple pages. Mocking frameworks can automate the creation of
multiple mock objects of the same type.
• Mocking objects with multiple interfaces. In some tests, where there are several dependencies between
classes of different types, you must create many mock objects of different classes. In such situations, it
is tedious to manually code many mock objects. Mocking frameworks can help by automatically
generating the objects from the interfaces that you specify.
In each unit test, you are interested in a small and specific area of functionality. Some properties and
methods of an interface will be crucial to your test, while others will be irrelevant. A mocking framework
enables you to specify irrelevant properties and methods in a given test. When the framework creates a
mock object for your test, it creates stubs for the irrelevant properties and methods. A stub is a simple
implementation with little code. In this way, the mocking framework frees you from having to implement
all the requirements of the interface laboriously.
Question: What is the difference between an IoC container and a mocking framework?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 06-13
Lesson 2
Implementing an Exception Handling Strategy
Unexpected events are likely to occur from time to time in any complex system, including MVC web
applications. Occasionally, such unexpected run-time events cause an error. When this happens, ASP.NET
or the .NET Framework generates an exception, which is an object that you can use to diagnose and
resolve the error. The exception contains information that you can use to diagnose the problem.
Exceptions that are not handled in your code will cause the web application to halt and an error message
to be displayed to the user. As a web developer, you need to know how to detect, handle, and raise
exceptions, and identify the cause of the problem. Visual Studio provides a broad range of tools for
debugging exceptions and improving the robustness of your code. You can also log exceptions to
databases and other stores, and use the .NET Framework code contracts to reduce the frequency of
exceptions.
Lesson Objectives
After completing this lesson, you will be able to:
• Explain how to raise and catch exceptions.
Unhandled Exceptions
When an exception is not explicitly handled by an application, the application stops and the user sees an
error message. In ASP.NET MVC applications, this error message is in the form of a webpage. You can
override ASP.NET default error pages to display your own error information to users.
If an unhandled exception arises while you are debugging the application in Visual Studio, execution
breaks on the line that generated the exception. You can use the Visual Studio debugging tools to
investigate what went wrong, isolate the problem, and debug your code.
Sometimes, you may also want to raise your own exceptions as a form of communication between parts
of your application. For example, consider an application that displays products on a website. In the
repository, you implement a FindProduct method that returns the product with a name that matches the
search string that is passed as an attribute. If the FindProduct method does not locate a product with the
specified name, you may wish to raise an exception. This approach enables code in the controller, which
calls the FindProduct method, to handle the event that no products are found. You can use the throw
keyword to raise errors in C# code.
MCT USE ONLY. STUDENT USE PROHIBITED
06-14 Testing and Debugging ASP.NET MVC 5 Web Applications
In MVC controllers, there are two methods to catch exceptions—the OnException method and the
[HandleError] annotation.
In the following code example, the OnException method is used to catch InvalidOperationException
objects.
use the [HandleError] annotation without properties, all exceptions are caught and sent to an MVC view
called Error.cshtml. This default error view should be created in the /View/Shared folder.
• View. By default, the [HandleError] annotation forwards users to the Error.cshtml view. You can
specify another view file by using the View property. By setting both the ExceptionType and View
properties, you can divert exceptions of specific types to views designed specifically to display them.
In the code example, the first [HandleError] annotation forwards NotImplementedException errors to
the NotImplemented view. All other errors are forwarded to the default error view.
Question: You are using the [HandleError] annotation to catch exceptions in your web application.
However, you realize that [HandleError] catches all exceptions, making it difficult for you to isolate a
specific issue. What can you do to narrow down the exceptions that the [HandleError] annotation is
catching?
To configure a custom error page for your application, use the top-level Web.config file. The custom error
page will be displayed when an exception in not handled by any try/catch block or [HandleError]
attribute.
o Off: Unhandled errors are displayed on the default ASP.NET error page.
MCT USE ONLY. STUDENT USE PROHIBITED
06-16 Testing and Debugging ASP.NET MVC 5 Web Applications
o On: Unhandled errors are displayed in the page you specify in the defaultRedirect attribute.
o RemoteOnly: In this mode, unhandled errors are displayed differently for browsers on remote
computers and browsers on the web server. In a production site, all browsers are remote and
errors are displayed on the page that you specify in the defaultRedirect attribute. In
development situations, the developer often browses to the site on the local computer. When an
error occurs, the developer is directed to the default ASP.NET error page, which includes
debugging information such as the stack trace. Use the RemoteOnly mode on development
computers.
• defaultRedirect: This attribute sets the name of the view that will be used to display unhandled
exceptions. When you create this view, place it in the Views/Shared folder.
The code in the following example enables custom errors and specifies that unhandled exceptions are
forwarded to the customError view.
Question: You have switched off custom errors in the Web.config file. When you run your application
without debugging, an exception is thrown in a try/catch block. What page displays the exception to the
user?
Logging Exceptions
Exceptions that you face during development can
be investigated and debugged by using the Visual
Studio debugging tools. In an ideal situation, no
exceptions would arise when your web application
is complete and deployed for users over the
Internet. However, in the real world, unforeseen
circumstances arise resulting in exceptions. For
example, database failures, network issues, and
configuration errors in any part of the system can
cause exceptions.
administrators and developers can assess the extent of the problem, remove the cause, and improve the
robustness of the code.
A common approach is to log errors to tables in a database. These tables can be a part of a single web
application database, or you can place them in a dedicated database away from product catalogs, user
profiles, and other information. By logging exceptions to a database, you create a list of exceptions that
can be easily searched and analyzed. You can also build a webpage to present these logged exceptions to
administrators so that they can access the details from a browser.
You should also consider sending email messages or other types of messages to administrators and
developers when exceptions occur. This approach ensures that administrators and developers hear of an
error very quickly. It does not require them to review the exceptions logged in the database. Frequently,
error handling code in live applications both logs to a database and send email messages to
administrators and developers.
• Create a custom base controller class for your web application. This class inherits from the
System.Web.Mvc.Controller base class.
• In your custom base controller class, override the OnException() method. Place you error logging
code in this method.
• When you create controllers, inherit from your custom base controller class, instead of
System.Web.Mvc.Controller.
In this way, you can write error logging code only once in the overridden OnExcpetion() method. This
catches exceptions from any of the inheriting controllers.
Question: You want to ensure that developers can review exception details that arise during debugging.
How should you approach error logging code?
MCT USE ONLY. STUDENT USE PROHIBITED
06-18 Testing and Debugging ASP.NET MVC 5 Web Applications
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 80 minutes
You will find the high level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD06_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD06_LAK.md.
o Test_PhotoGallery_No_Parameter: This test checks that when you call the _PhotoGallery
action without any parameters, the action passes all the photos in the context to the
_PhotoGallery partial view.
o Test_PhotoGallery_Int_Parameter: This test checks that when you call the _PhotoGallery action
with an integer parameter, the action passes the corresponding number of photos to the
_PhotoGallery action.
• Implement a repository.
Note: The tests you add to the solution in this exercise will improve the quality of code and
prevent bugs as development proceeds. However, this exercise does not conform to the
principles of TDD because the PhotoController class already exists. In TDD, you would create
these and other tests first, and then create a PhotoController class that passes the tests.
Review Question
Question: You want to ensure that the PhotoController object passes a single Photo object
to the Display view, when a user calls the Search action for an existing photo title. What unit
tests should you create to check this functionality?
Tools
NinJect, StructureMap. These are Inversion of Control (IoC) containers, also known as Dependency
Injection (DI) frameworks. They create non-test implementations of interfaces in your web application.
Moq, NSubstitute. These are mocking frameworks. They automate the creation of test doubles for unit
tests.
Best Practices
• If you are using TDD or Extreme Programming, define each test before you write the code
that implements a requirement. Use the test as a full specification that your code must
satisfy. This requires a full understanding of the design.
• Investigate and choose a mocking framework to help you create test double objects for use
in unit tests. Though it may take time to select the best framework and to learn how to code
mock objects, your time investment will be worth it over the life of the project.
• Do not be tempted to skip unit tests when under time pressure. Doing so can introduce bugs
and errors into your system and result in more time being spent debugging.
Module 7
Structuring ASP.NET MVC 5 Web Applications
Contents:
Module Overview 07-1
Module Overview
An MVC web application can grow large and complex and the application can contain many types of
information that relate to each other in complicated ways. A key challenge for such web applications is to
ensure that users can easily locate the information that interests them. Although a search tool is helpful,
you should design your web application in such a way that users can navigate to the page they need
through a short sequence of links. At each level, users must know what link to click next. The URLs that
users see in the Address bar must be readable and understandable. You need to understand how to
present the model classes you have designed in a way that is logical to the user. You also need to ensure
that Internet search engines can crawl and analyze your web application structure, so that your
application content appears close to the top of the search engine results. You can achieve these goals by
learning about ASP.NET routing and navigation.
Objectives
After completing this module, you will be able to:
• Add routes to the ASP.NET routing engine and ensure that URLs are user-friendly throughout an MVC
web application.
Lesson 1
Analyzing Information Architecture
When you analyze use cases and user stories to plan a model for your web application, you must
determine the kinds of objects that your web application will manage. For example, if your web
application provides technical documentation for a product, you can plan model classes such as
installation guides, user guides, frequently asked questions (FAQs), FAQ answers, categories, comments,
and other model classes. The model imposes a logical structure of objects on the web application.
However, you must also consider how users expect information to be structured. Users may expect a
hierarchical structure, in which FAQs, FAQ answers, and comments are presented under the product they
relate to. When you create a complex MVC web application, you need to know how to present model
classes in a logical manner, so that your web application is user-friendly.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe information architecture.
• Describe search engine optimization and its importance for web developers.
Information architecture is a logical structure for the objects your web application manages. You should
design such architecture in a way that users can find content quickly without understanding any technical
aspects of your web application. For example, users should be able to locate a technical answer about
their product without understanding the database structure or the classes that constitute the model.
The development team has identified the following simple user stories:
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-3
• Customers have a certain problem with their boilers. They want to find a specific FAQ answer that
solves the problem. They know the boiler product name and the fuel, but not the product number.
They visit the web application and navigate to the boiler name. They click the FAQ for their boiler
name and locate the answer that they need.
• Engineers need the latest installation manual for a boiler. They know the boiler product number,
product name, and fuel type. They visit the site and navigate to the boiler name. They click the
Manuals link and locate the installation manual.
• Engineers have web applications, which they want to link to a specific boiler name. You want to
ensure that the URL is simple and readable for customers and engineers.
• Furnace. Each furnace object is a product manufactured and sold by the company.
• Category. Categories organize the furnaces by type. For example, you can have categories such as
oil-fired, gas-fired, and solid fuel.
• FAQ. Each FAQ relates to a single furnace. Each furnace can have many questions. The class includes
both Question and Answer properties.
• Installation Manual. Each furnace has a single installation manual in the form of a PDF document.
• User Manual. Each furnace has a single user manual in the form of a PDF document.
• Category
o Furnace
FAQ
User Manual
Installation Manual
• Breadcrumb Trails. A breadcrumb trail is a navigation control that shows the user where they are in
the web application. Usually a breadcrumb trail shows the current pages and all the parent pages in
the hierarchy, with the home page as the top level. Breadcrumb trails enable you to understand how
a page fits in with the information architecture shown in menus and tree views.
The types of navigation controls you build in your web application depend on how you expect users to
find information.
MCT USE ONLY. STUDENT USE PROHIBITED
07-4 Structuring ASP.NET MVC 5 Web Applications
In MVC web applications, the default configuration is simple, but it is based on controllers, actions, and
parameters. The following are some example URLs that follow this default pattern:
• http://site/Furnace/Details/23: This URL links to the Furnace controller and the Details action, and it
displays the furnace with the ID 23.
• http://site/FAQQuestion/Details/234: This URL links to the FAQQuestion controller and the Details
action, and it displays the FAQ with the ID 234.
As you can see, the web application user is required to understand how controllers, actions, and action
parameters work, to formulate URLs themselves. Instead, users can use URLs that are easier to understand,
such as the following, because they reflect the information hierarchy:
• http://site/OilFired/HotBurner2000: This URL links to a Furnace by specifying the fuel category and the
product name. Customers and engineers can understand these values.
web bot. If you understand the priorities that web bots and search engine indexes use to order search
results, you can create a web application that conforms to those priorities and thereby appears high in
search engine results.
• Ensure that each webpage in your web application has a meaningful <title> element in the <head>
section of the HTML.
• Ensure that you include a <meta name="keywords"> tag in the <head> element of each page. The
content attribute of this element should include keywords that describe the content of the page
accurately.
• Ensure that you include a <meta name="description"> tag in the <head> element of each page. The
content attribute of this element should include a sentence that describes the content of the page
accurately.
• Ensure that the <title> element and the <meta> elements are different for each page in your web
application.
• Choose a domain name that includes one or more of your most important keywords.
• Ensure that keywords appear in the <h1>, <h2>, or <h3> elements of your webpage.
• Ensure that navigation controls enable web bots to crawl your entire web application. For example,
you may have content in your site that users can only find with the search tool, not by clicking
through links. As web bots cannot use search tools, this content will not be indexed.
• Ensure that URLs do not include GUIDs or long query text.
As an ASP.NET MVC developer, you must understand SEO principles and use them whenever you write
code, to ensure that you do not damage the search engine positioning of your web application. Views are
critical to SEO because they render <meta> tags, and <title> elements. Routes and the configuration of
the routing engine are also critical, because, by using routes, you can control the URLs that your web
application generates.
Question: A developer creates a partial view that contains <meta> tags and <title> tags. The developer
uses this partial view on every page in the web application. Do these actions conform to SEO best
practices?
MCT USE ONLY. STUDENT USE PROHIBITED
07-6 Structuring ASP.NET MVC 5 Web Applications
Lesson 2
Configuring Routes
ASP.NET enables developers to control the URLs that a web application uses, to link the URLs and the
content by configuring routes. A route is an object that parses a requested URL, and it determines the
controller and action to which the request must be forwarded. Such routes are called incoming routes.
HTML helpers also use routes when they formulate links to controllers and actions. Such routes are called
outgoing routes. You need to know how to write code that adds a new route to your application. You also
need to know how the routing engine interprets a route so that requests go to the appropriate
controllers, and users see meaningful URLs.
Lesson Objectives
After completing this module, you will be able to:
• To formulate URLs in webpage links and other elements. When you use helpers such as
Html.ActionLink() and Url.Action() in MVC views, the helpers construct URLs according to the
routes in the routing table. These are called outgoing URLs.
When you create an MVC web application in Visual Studio by using a project template, the application
has a default route. You must understand this default route before you consider adding extra routes to
manipulate URLs in the application.
Note: You can use routes and the routing engine to govern relative URLs in any ASP.NET
application and not just in those that use the MVC programming model.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-7
• The first segment is interpreted as the name of the controller. The routing engine forwards the
request to this controller. If a first segment is not specified, the default route forwards the request to a
controller called Home.
• The second segment is interpreted as the name of the action. The routing engine forwards the
request to this action. If a second segment is not specified, the default route forwards the request to a
controller called Index.
• The third segment is interpreted as an ID value, which is passed to the action as a parameter. The
parameter is optional, so if a third segment is not specified, no default value is passed to the action.
You can see that when the user requests the URL, http://www.advworks.com/photo/display/1, the default
route passes the ID parameter 1 to the Display action of the Photo controller.
The following code shows how the default route is implemented in new ASP.NET MVC 5 applications.
Custom Routes
Developers add their own custom routes to a web application for two main reasons:
• To make URLs easier for site visitors to understand. A URL such as
http://www.advworks.com/photo/display/1 is logical to the visitor, but it requires some knowledge to
formulate such URLs. In this case, to type the right URL in the Address bar of the web browser, the
user must know some information. This information includes the controller name, Photo, the action
name, Display, and the ID of the photo of interest. If you use Globally Unique Identifiers (GUIDs) in
the database, the ID segment of the URL can be long and difficult to remember. Ideally, you should
consider what users know and create routes that accept that information. In this example, users may
know the title of a photo that they had seen earlier in your application. You should create a route that
can interpret a URL such as http://www.advworks.com/photo/title/My%20Photo%20Title, and forward
the URL to an appropriate action to display the right photo. Although users usually click links to make
requests, friendly URLs like these make a site easier to use and link to from other sites.
• To improve search engine rankings. Search engines do not prioritize webpages that have GUIDs or
long query text in the URL. Some web bots do not even crawl such links. In addition, some search
engines boost a page’s ranking when one or more of its keywords appear in the URL. User-friendly
URLs are therefore a critical tool in SEO.
1. An MvcHandler object creates a controller factory. The controller factory is the object that
instantiates a controller to respond to the request.
2. The controller factory consults the routing table to determine the right Controller class to use.
3. The controller factory creates a Controller object, and the MvcHandler calls the Execute method in
that controller.
4. The ControllerActionInvoker examines the request URL and consults the routing table to determine
the action in the Controller object to call.
5. The ControllerActionInvoker uses a model binder to determine the values that should be passed to
the action as parameters. The model binder consults the routing table to determine if any segments
of the URL should be passed as parameters. The model binder can also pass parameters from a
posted form, from the URL query text, or from uploaded files.
6. The ControllerActionInvoker runs the action. Often, the action creates a new instance of a model
class, perhaps by querying the database with the parameters that the invoker passed to it. This model
object is passed to a view, to display results to the user.
As you can see, you can use routes to manage the behavior of controller factories, action invokers, and
model binders, because all these objects refer to the routing table. MVC is highly extensible; therefore,
developers can create custom implementations of controller factories, action invokers, and model binders.
However, by using routes, you can usually implement the URL functionality that you need with the default
implementations of these classes. You should ensure that routes cannot implement your required
functionality before you plan to customize controller factories, action invokers, or model binders.
Question: A user wants to edit a comment that the user created in your MVC application. You have not
created any custom routes. What URL do you think the user must request, to see the edit view with the
right comment?
Properties of a Route
Before you can add a route, you must understand the properties of a route. This is to ensure that these
properties match the URL segments correctly and pass requests and parameters to the right location. The
properties of a route include the following:
• Name. This string property assigns a name to a route. It is not involved in matching or request
forwarding.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-9
• URL. This string property is a URL pattern that is compared to a request, to determine if the route
should be used. You can use segment variables to match a part of the URL. You can specify a segment
variable by using braces. For example, if you specify the URL, “photo/{title}”, the route matches any
request where the relative URL starts with the string, “photo/”, and includes one more segment. The
segment variable is “title” and can be used elsewhere in the route.
• Constraints. Sometimes you must place extra constraints on the route to ensure that it matches only
with the appropriate requests. For example, if you want relative URLs in the form, “photo/34”, to
specify a photo with the ID “34”, you must use a URL property like “photo/{id}”. However, observe
that this URL pattern also matches the relative URL, “photo/create”, because it has one extra segment.
For IDs, you must constrain the URL to match only segments comprising digits. You can do this by
adding a constraint to the route. The Constraints property enables you to specify a regular
expression for each segment variable. The route will match a request only if all the segment variables
match the regular expressions that you specify.
• Defaults. This string property can assign default values to the segment variables in the URL pattern.
Default values are used for segment variables when the request does not specify them.
Observe that the URL pattern specifies three segments: {controller}, {action}, and {id}. This means that a
relative URL in the form, “photo/display/23”, will be sent to the Display action of the PhotoController
class. The third segment will be passed as a parameter to the action method. Therefore, if the Display
action accepts a parameter named id, the value, 23, will be passed by MVC.
In the defaults property, the {id} segment is marked as optional. This means that the route still matches a
relative URL, even if no third segment is specified. For example, the route matches the relative URL,
“photo/create”, and passes the URL to the Create action of the PhotoController class.
The defaults property specifies a default value of “Index” for the {action} segment. This means that the
route still matches a relative URL, even if no second segment is specified. For example, the route matches
the relative URL, “photo”, and passes the URL to the Index action of the PhotoController class.
Finally, the defaults property specifies a default value of “Home” for the {controller} segment. This means
that the route still matches a relative URL, even if no segments are specified, that is, if there is no relative
URL. For example, the absolute URL, “http://www.advworks.com”, matches this route, and the URL is
passed to the Index action of the HomeController class.
As you can see, with the default route in place, developers build the web application’s home page by
creating a controller named, HomeController, with an action named, Index. This action usually returns a
view called, Index, from the Views/Home folder.
In the following code example, a constraint is used to ensure that only digits match the {id} segment
variable.
A Custom Route
routes.MapRoute(
name: "PhotoRoute",
url: "photo/{id}",
defaults: new { controller = "Photo", action = "Details" },
constraints: new { id = "[0-9]+" }
);
Observe that the URL pattern in the route matches any relative URL that starts with “photo/” and has one
or more segments. However, in the constraints property, the route specifies a regular expression for the
{id} segment variable. This regular expression matches only if the segment is composed of digits that
range from 1 through 9. If the user requests the relative URL, “photo/234”, then this route matches, and
the routing engine forwards the request to the Details action of the PhotoController class. If the user
requests the relative URL, “photo/create”, then this route does not match and a subsequent route must be
used to forward the request.
Precedence of Routes
Routes are evaluated by the routing engine in the order with which they are added to the
RouteTable.Routes collection. If a route matches, the routing engine uses it and does not evaluate any
later route in the collection. If a route does not match, the routing engine ignores it and evaluates the
next route in the collection. For this reason, you must add routes to the RouteTable.Routes collection in
the appropriate order. You can add the most specific routes first, such as routes that have no segment
variables and no default values. Routes with constraints should be added before routes without
constraints.
The route named "Default" matches any request, including those with no relative URL. This default route
should be the last that you add to the RouteTable.Routes collection. If the routing engine evaluates this
route, the route is always used. Any routes added after the “Default” route are never used.
Question: A developer has removed all code from the Application_Start() method in Global.asax.cs.
When the developer runs the application, he or she receives 404 errors for any request, regardless of the
relative URL. Why does this occur?
Segment variables or default values with other names have no special meaning to MVC and are passed to
actions. You can access the values of these variables by using one of two methods: the RouteData.Values
collection or by using model binding to pass values to action parameters.
• In RouteConfig.cs, you have defined a route with the URL pattern “{controller}/{action}/{title}”.
• The user requests the relative URL, “photo/edit/my%20photo”.
The RouteData.Values collection contains the following values, which you can use in the action method:
The default MVC action invoker is a class named, ControllerActionInvoker. This invoker uses a class
named, DefaultModelBinder, to pass the appropriate parameters to actions. This model binder uses the
following logic to pass parameters:
1. The binder examines the definition of the action to which it must pass parameters. In the example,
the binder determines that the action requires an integer parameter called, PhotoID.
2. The binder searches for values in the request, which can be passed as parameters by name. In the
example, the binder searches for integers because the action requires integers. The binder searches
for values in the following locations in sequential order:
a. Form Values. If the user fills out a form and clicks the Submit button, the binder can find
parameters in the Request.Form collection.
b. Route Values. If the matched route includes the segment variable {photoid}, the binder can find
the value for the PhotoID parameter in the RouteData.Values collection. This match is case-
insensitive.
c. Query Strings. If the user request includes named parameters after a question mark, the binder
can find these parameters in the Request.QueryString collection.
d. Files: If the user request includes uploaded files, these files can be used as parameters in an
action. File parameters in actions must use the HttpPostedFileBase type.
Therefore, you can use the default model binder to pass parameters to action strings. If the name of an
action method parameter matches the name of a route segment variable, the model binder passes the
parameter automatically.
Optional Parameters
Sometimes, you want requests to match a route, regardless of whether parameter values are supplied. For
example, you might want to enable users to specify a color for a product.
In the following example, the route added includes an optional color parameter.
MCT USE ONLY. STUDENT USE PROHIBITED
07-12 Structuring ASP.NET MVC 5 Web Applications
The default values specify that {color} is optional. If the relative URL has three segments, the route
matches, and the third segment is passed to the RouteData.Values["color"] value. If the relative URL has
only two segments, the route matches, because the {color} is optional. In this case, the
RouteData.Values["color"] value does not exist. If the relative URL has only one segment, the route does
not match.
Question: A developer has replaced the default model binder with a custom model binder. Now, several
action methods are throwing exceptions on lines that use action parameters. How can you fix this bug?
Demonstration Steps
You will find the steps in the “Lesson 2: Configuring Routes“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD07_DEMO.md.
The following code shows how to create a fake HTTP context object to use as a test double.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-13
//The constructor enables you to specify a request URL and an Application path in
the test
public FakeHttpContextForRouting(string appPath = "/", string requestUrl = "~/")
{
//Create new fake request and response objects
_request = new FakeHttpRequestForRouting(appPath, requestUrl);
_response = new FakeHttpResponseForRouting();
}
}
}
• Arrange. In the Arrange phase of the test, you can create a new HTTP context from your test double
class. You can set the request URL for this object to be the URL you want to test. You can then create
a new route collection and call the RouteConfig.RegisterRoutes() method in your web application.
• Act. In the Act phase, you can test the routes by calling the GetRouteData() method of the route
collection. You can then pass the fake HTTP context to this method.
• Assert. In the Assert phase, you can use the RouteData.Values collection to check that the controller,
action and other values are assigned correctly.
In the following example unit test, the default route is checked. The request URL has only a single
segment and the test asserts that this segment is passed as the controller name.
// Act
RouteData routeData = routes.GetRouteData(context);
// Assert
Assert.AreEqual("ControllerName", routeData.Values["controller"]);
Assert.AreEqual("Index", routeData.Values["action"]);
Assert.AreEqual(UrlParameter.Optional, routeData.Values["id"]);
}
Question: You are writing a unit test to check your web application’s routing table. You want to ensure
that the request is passed to an action method called, “Edit”. What line of code would you use in the
Assert phase of the test to check this fact?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-15
Lesson 3
Creating a Navigation Structure
A navigation structure is a logical hierarchy of webpages, which enables users to browse to the
information that interests them. In simple web applications, the design of the navigation structure is also
usually simple. As your web application grows, it becomes difficult to present menus and navigation
controls that show the users clearly what their next click should be, at every step. You need to understand
how to build menus, which help users understand where they are in your site and where to go next. You
can do this by building menus and breadcrumb controls.
Lesson Objectives
After completing this lesson, you will be able to:
After designing the information architecture, you must present it in your web application. You can add
routes to ensure that URLs reflect your information architecture. Similarly, you must add navigation
controls to present the information architecture in the body of each webpage. The navigation controls
you build are the primary means by which users browse your web application and locate content. You
should ensure two things with these navigation controls:
• An obvious next step. You should ensure that users can easily decide what link to click, on each page.
To achieve this aim, you can consider use cases. For each use case, you can list what the user knows
when they arrive at your web application. The user should be able to choose the right link without
any specialist or technical knowledge. For example, avoid basing your links on any kind of technical
jargon, unless you know that your audience understands it.
• A clear context. In a simple web application with only one or two levels in the information
architecture, users can easily keep track of where they are. In larger web applications with many
MCT USE ONLY. STUDENT USE PROHIBITED
07-16 Structuring ASP.NET MVC 5 Web Applications
levels, you must provide navigation controls, which show users where they are and how to navigate
back up the hierarchy. Tree views and breadcrumb controls perform this function well.
• Top menus. Often placed at the top of the page or immediately beneath the application branding,
top menus link to the main areas of your web application. In some applications, each item in the top
menu has a submenu with links to lower level items and pages.
• Tree views. A tree view is a hierarchical menu that can display many items in multiple levels in your
web application. By default, a tree view often displays only one or two levels of the information
architecture. Users can expand lower levels to find the content they need. Tree views enable users to
explore multiple levels on a single page. Tree views can also show clearly the position of the current
page, in the hierarchy.
• Breadcrumb trails. Often presented as a horizontal sequence of links across the top of a webpage, a
breadcrumb trail shows the current page and its parents in all the higher levels of the hierarchy.
Breadcrumb trails show the current position of the user, in the context of the web application and
enable users to navigate to higher, less specific pages.
• Footer menus. The page footer is often not visible when a user arrives on a page. The user must scroll
to the end of the page to see the footer. The footer is often used as a location for important, but not
business-critical, links. For example, links to copyright and other legal information, links to parent
companies, and links to site maps are often placed in the footer menu.
Note: The MVC Site Map Provider is a component by Maarten Balliauw that is not included
in MVC web applications, by default. You can find it in the NuGet package manager by searching
for “MvcSiteMapProvider.MVC5”.
Question: Analysis of web logs has shown that visitors to your web application can navigate to low-level
pages in your information architecture, quickly and easily. However, they subsequently find other pages
by returning to the home page and navigating the entire hierarchy again from the top, or else they use
the search tool. How can you enable users to navigate to higher levels without starting from the home
page again?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-17
The following code example shows how to configure the site map provider.
actionMethodParameterResolver="MvcSiteMapProvider.DefaultActionMethodParameterResolver,
MvcSiteMapProvider"
aclModule="MvcSiteMapProvider.DefaultAclModule, MvcSiteMapProvider"
siteMapNodeUrlResolver="MvcSiteMapProvider.DefaultSiteMapNodeUrlResolver,
MvcSiteMapProvider"
siteMapNodeVisibilityProvider="MvcSiteMapProvider.DefaultSiteMapNodeVisibilityProvider,
MvcSiteMapProvider"
siteMapProviderEventHandler="MvcSiteMapProvider.DefaultSiteMapProviderEventHandler,
MvcSiteMapProvider"
/>
</providers>
</siteMap>
Note that you can configure the name of the XML file where the site map is stored, enable security
trimming, and configure caching.
Additional Reading: For complete details of the configuration values you can use with the
MVC Site Map Provider, together with other documentation, go to
http://go.microsoft.com/fwlink/?LinkID=288963&clcid=0x409
MCT USE ONLY. STUDENT USE PROHIBITED
07-18 Structuring ASP.NET MVC 5 Web Applications
The following example shows simple information architecture as described in an MVC site map provider
site map file.
</mvcSiteMap>
Question: You use the MVC Site Map Provider. Your boss notices that an incorrect link appears in the
highest menu and the tree view on every page in your web application. Your boss asks you to fix every
page in the web application. What steps should you take?
In this example, the first parameter specifies that the menu does not start from the current node. The
menu starts from the top-level node, which is usually the home page of the web application. The second
parameter specifies that the starting node does not display as a child node at the same level as second-
level nodes. The third parameter specifies that the starting node displays in the menu.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 07-19
You can also use the Html.MvcSiteMap() helper to render a breadcrumb control, as displayed in the
following code.
The Html.MvcSiteMap() helper also includes functions that you can use to render node titles and
complete site maps.
Additional Reading: For complete reference documentation that details the Html.MvcSiteMap()
helper and its functions, go to http://go.microsoft.com/fwlink/?LinkID=288964&clcid=0x409
Question: What are some of the benefits of using the Html.MvcSiteMap() helper?
Demonstration Steps
You will find the steps in the “Lesson 3: Creating a Navigation Structure“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD07_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
07-20 Structuring ASP.NET MVC 5 Web Applications
You have been asked to ensure that the URLs of the following forms work to display a photo:
• ~/photo/display/PhotoId. In this form of URL, PhotoId is the database ID of the photo object. This
form of URL already works because it matches the default route.
• ~/photo/PhotoId. In this form of URL, PhotoId is the database ID of the photo object. This is the
logical URL to enter when you know the ID of the photo that you want to access.
• ~/photo/title/PhotoTitle. In this form of URL, PhotoTitle is the title of the photo object. This is the
logical URL to enter when you know the title of the photo that you want to access.
You have also been asked to implement the following navigation controls in the Photo Sharing
application:
Objectives
After completing this lab, you will be able to:
• Add routes to the ASP.NET Routing Engine in an ASP.NET MVC application.
Lab Setup
Estimated Time: 35 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD07_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD07_LAK.md.
• Add the MVC site map provider to your Photo Sharing application.
• Use the MVC site map provider to create a menu and a breadcrumb control.
At this stage of development, most of the main areas in the Photo Sharing Application are not yet built;
therefore, the menu will show only the home page and the All Photos gallery. Your team will add new
nodes to the site map as areas of the site are completed.
Review Questions
Question: Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
You have implemented the MVC Site Map Provider in your web
application and used it to build menus and breadcrumb trails
with which users can navigate the logical hierarchy. MVC
automatically takes routes from the MVC Site Map Provider so
the same hierarchy is used in URLs.
Question: You want to ensure that when the user specifies a relative URL in the form,
“customer/3546”, the request is forwarded to the DisplayByID() action in the
CustomerController. You also want to ensure that when the user specifies a relative
URL in the form, “customer/fullname”, the request is forwarded to the DisplayByName()
action in the CustomerController. What routes should you add?
Best Practices
• The default route is logical. However, it requires knowledge of controllers and actions for
users to understand URLs. You can consider creating custom routes that can be understood
with information that users already have.
• You can use breadcrumb trails and tree view navigation controls to present the current
location of a user, in the context of the logical hierarchy of the web application.
• You can use unit tests to check routes in the routing table, similar to the manner with which
you use tests to check controllers, actions, and model classes. It is easy for a small mistake to
completely change the way URLs are handled in your web application. This is because new
routes, if poorly coded, can override other routes. Unit tests highlight such bugs as soon as
they arise.
Module 8
Applying Styles to ASP.NET MVC 5 Web Applications
Contents:
Module Overview 08-1
Module Overview
While building web applications, you should apply a consistent look and feel to the application. You
should include consistent header and footer sections in all the views. ASP.NET MVC 5 includes features
such as cascading style sheets (CSS) styles and layouts that enhance the appearance and usability of your
web application. ASP.NET MVC 5 also includes features such as mobile-specific views that allow you to
build applications for different browsers or mobile devices.
Objectives
After completing this module, you will be able to:
• Apply a consistent layout to ASP.NET MVC 5 applications by using CSS and layout.
Lesson 1
Using Layouts
You need to build multiple views to support the operations of the application, such as creating an order
and querying order history. However, several maintenance issues arise while changing the common part
of the application layout, because of which you need to update each view. To resolve these maintenance
issues, you can build a common module or a shared view. A shared view that helps to store the
application logic is called a layout. ASP.NET MVC 5 includes features that help simplify the process of
creating and using layouts. You can further simplify the application management process by using the
_ViewStart file, to apply the layout to each view, instead of individually editing each view.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe layouts.
Question: What are some common scenarios when you would use layouts?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 08-3
Creating a Layout
While creating layouts, you need to store the
layout files in the \Views\Shared folder of the
project. The \Views\Shared folder is the default
location, where you can store common view files
or templates.
A Layout View
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html
In the preceding example, the @RenderBody() method indicates to the rendering engine where the
content of the view goes.
ViewBag is an object that the layout and view shares. You can use the ViewBag object to pass
information between a view and a layout. To pass information, you need to add a property to the
ViewBag object, in the ViewPage of the ViewController or View file, and use the same property in the
layout file. Properties help you control the content in the layout, to dynamically render webpages from
the code in the view file. For example, consider that the template uses the ViewBag.Title property to
render the <title> content in the view. This property helps define the Title property of the ViewBag
object in the view and retrieve the property in the layout. This retrieval is possible because the code in the
view file runs before the layout runs.
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div id="menu">
@RenderSection("MenuBar",required:false)
</div>
<div>
@RenderBody()
</div>
MCT USE ONLY. STUDENT USE PROHIBITED
08-4 Applying Styles to ASP.NET MVC 5 Web Applications
</body>
</html>
The MenuBar parameter in the RenderSection() helper method specifies the name of the section that
you want to render in the layout. The required parameter is optional; it allows you to determine if the
section you render is required. Consider that a section is required, and you do not implement the section
in the layout file. In this case, ASP.NET MVC 5 displays the Section not defined exception at runtime.
Implementing sections in a layout file makes it easier to track content errors. If a section is not required,
you can choose to not include it in the layout.
Linking to a View
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
<h2>Details</h2>
You can use the ViewBag.Title property to pass page title information from the view to the layout. You
can define other properties along with the ViewBag object, such as <meta> elements in the <head>
section, and enable them to pass information to the layout.
If you have multiple sections in the layout file, you define the content of the sections by using the
@section directive. The following code illustrates how to use the @section directive.
<h2>Details</h2>
@section MenuBar {
<p> this is menu</p>
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 08-5
In the preceding example, you set the layout file to display sections at the top of each view file. Usually,
you have the same layout across the entire web application or section. You can define the layout for an
application or section, by using the _ViewStart file. During runtime, the code in the _ViewStart file runs
before all the other views in the web application. Therefore, you can place all common application logics
in the _ViewStart file.
To use the _ViewStart file, you need to add the _ViewStart.cshtml file in the \Views folder of your project.
The following code illustrates the contents of the _ViewStart file.
Lesson 2
Applying CSS Styles to an MVC Application
Cascading Style Sheets (CSS) is an industry standard for applying styles to HTML pages. Different methods
of applying CSS to a webpage are available. These methods include external CSS file, inline CSS, and CSS
code block in HTML. Developers usually use an external CSS file, because this file is shared across multiple
pages and it helps apply a consistent style across the application. You need to know how to import styles
into a web application, to ensure consistency in the appearance of the application.
Lesson Objectives
After completing this lesson, you will be able to:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link href="~/Views/Shared/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="menu">
@RenderSection("MenuBar",required:false)
</div>
<div>
@RenderBody()
</div>
</body>
</html>
CSS selectors help browsers to determine how the CSS styles should be applied. You can use various
selectors, such as class and id selectors, to apply styles to HTML elements.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 08-7
Using a Class
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
<h2>Details</h2>
@section MenuBar {
<p class=”menu”> this is menu</p>
}
The following CSS snippet shows how to create the class selector.
CSS id Selector
You can use the CSS id selector to specify a style for any unique element in your HTML code. To apply the
id selector to an HTML element, you need to add the id attribute and a unique name to the HTML
element. You can use the #<id> syntax to add the style in the CSS file.
<h2>Details</h2>
@section MenuBar {
<p id="leftmenu"> this is menu</p>
}
The following CSS snippet shows how to create the CSS id selector.
Creating an ID Style
#leftmenu
{
font-size:16px;
}
Question: What are some common scenarios when you would use the class selector? What are some
common scenarios when you would use the id selector?
MCT USE ONLY. STUDENT USE PROHIBITED
08-8 Applying Styles to ASP.NET MVC 5 Web Applications
• Create a layout.
• Apply the layout to an MVC view.
Demonstration Steps
You will find the steps in the “Lesson 2: Applying CSS Styles to an MVC Application“ section on the
following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD08_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 08-9
Lesson 3
Creating an Adaptive User Interface
ASP.NET MVC 5 applications facilitate adaptive user interface to render content on different devices.
Adaptive user interface is a type of user interface that renders content based on the capability of the
target web browser or device. You need to ensure that your application supports mobile devices, so that it
reaches all types of audience. You also need to know how to use media queries and mobile-specific views
to ensure that your application is effective on mobile devices.
Lesson Objectives
After completing this lesson, you will be able to:
• Explain how you can use MVC 5 templates to render views based on mobile device screen size.
Additional Reading: For more information about the viewport attribute, visit:
http://go.microsoft.com/fwlink/?LinkID=288967&clcid=0x409
The viewport tag is a meta tag that helps to control the width and height of webpages, while it renders
to web browsers.
The width and height properties help to specify the width and height of the virtual viewport window.
You can specify the width in pixels. You can use the keyword device-width to enable the content to fit
the native screen size of the browser.
The initial-scale property controls the initial scale or zoom level of the webpage. The maximum-scale,
minimum-scale, and user-scalable properties control the other scalability features of the webpage.
MCT USE ONLY. STUDENT USE PROHIBITED
08-10 Applying Styles to ASP.NET MVC 5 Web Applications
Question: How can you control the size of the virtual viewport window?
You can also apply a media query in the <link> element. The following example illustrates how to include
a media query in a <link> element.
You can use CSS media queries to apply CSS styles when the screen size is less than 500 pixels. However,
you can use CSS media queries only for the screen layout, but not the print layout.
The following table describes properties that you can include in a media query.
Property Description
width The width of the targeted display area, which includes the browser window in
desktop and mobile devices. In desktop computers, when you resize the browser
window, the width of the browser changes. However, on most mobile browsers,
you cannot resize the browser window. This implies that the width of the browser
remains constant.
height The height of the targeted display area, which includes the browser window in
desktop and mobile devices.
device-width The width of the entire screen of a device. For a desktop with a screen resolution of
1,024x768, the device-width is usually 1,024 pixels.
device-height The height of the entire screen of a device. For a desktop with a screen resolution
of 1,024x768, the device-height is usually 768 pixels.
orientation The orientation of the device. If the device-width is larger than the device-height,
the orientation value is set to landscape; otherwise, it is set to portrait.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 08-11
Property Description
device-aspect- The ratio of the device-width and device-height properties. The following
ratio example illustrates the device-aspect-ratio for a device with a screen resolution of
1,280x720.
@media screen and (device-aspect-ratio: 16/9) { }
@media screen and (device-aspect-ratio: 1280/720) { }
@media screen and (device-aspect-ratio: 2560/1440) { }
color The number of bits per color component of the device. If the device is not a color
device, the value is zero.
color-index The number of entries in the color lookup table, of the output device.
monochrome The number of bits per pixel in a monochrome frame buffer. For non-monochrome
devices, this value is zero.
resolution The resolution of the output device, or the density of the pixels. The common units
for this property include dpi and dpcm.
grid The property that detects whether the output is in the grid or bitmap format. Grid-
based devices return a value of one; all other devices return a value of zero.
Question: Why would you choose to use CSS media queries, instead of using C# code, to define styles for
specific browsers?
Consider that your web application includes a layout that is specific to a browser. In this case, you can
create browser-specific views for that browser by checking the UserAgent string of that browser. The
UserAgent string helps identify a browser.
Question: Why would you choose device-specific display modes over CSS media queries?
MCT USE ONLY. STUDENT USE PROHIBITED
08-12 Applying Styles to ASP.NET MVC 5 Web Applications
To resolve these issues, your manager asked you to implement the following user interface features:
• A layout for all webpages. The layout should include common elements, such as the main menu and
breadcrumb controls, which should appear on every page of the application.
• A style sheet and images for all webpages. The web design team has provided an HTML mockup
application to show how the final product should look. This mockup includes a style sheet and image
files. You need to import these files and apply them to every page of the application.
• A mobile-specific view. The web application should be accessible from mobile devices such as mobile
phones and tablets. In particular, you need to ensure that devices with narrow screens can access
photos easily.
Objectives
After completing this lab, you will be able to:
• Ensure that the web application renders smoothly on screens of different sizes and aspect ratios.
Lab Setup
Estimated Time: 60 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD08_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD08_LAK.md.
• Create a new layout and link the application to the view by using a _ViewStart.cshtml file.
• Modify the home index and photo display views to use the new layout.
• Browse through the resulting web application.
• Examine a mockup web application that shows the look-and-feel the web designers have created for
the Photo Sharing application.
• Import a style sheet, with the associated graphic files from the mockup application, to your web
application, and then update the HTML element classes to apply those styles to the elements in views.
• Examine the changes to the user interface after the styles have been applied.
Question: When you first viewed the site as a mobile browser in Exercise 3, what are the
problems you came across with the display of the site heading and menu?
MCT USE ONLY. STUDENT USE PROHIBITED
08-14 Applying Styles to ASP.NET MVC 5 Web Applications
Review Question
Question: You are building an application, which needs to work in different mobile devices,
Windows, and Mac. You want to reduce the effort for maintaining the code which is required
for different devices and you want to ensure that it would work with new browsers. What
should you do?
Module 9
Building Responsive Pages in ASP.NET MVC 5 Web
Applications
Contents:
Module Overview 09-1
Module Overview
Many web applications need to display large amount of information and graphics. Large volumes of data
make web applications take longer to load. Instead of having all the elements on the page load multiple
times, you can implement caching in your web applications to reduce the need to repeatedly load the
same elements. You can also use partial page updates to reduce the need to load the entire webpage, by
enabling the application to refresh only specific sections of the webpage.
Objectives
After completing this module, you will be able to:
• Implement partial page updates that help reduce the need to reload entire pages.
• Implement caching to reduce the loading time of the different elements of a webpage.
MCT USE ONLY. STUDENT USE PROHIBITED
09-2 Building Responsive Pages in ASP.NET MVC 5 Web Applications
Lesson 1
Using AJAX and Partial Page Updates
While developing web applications, to update individual sections in the page, you may need to reload the
entire webpage. Asynchronous JavaScript and XML (AJAX) in ASP.NET MVC 5 enables partial page
updates, to help update sections of a webpage, without reloading the entire page. The Ajax.ActionLink
helper helps implement partial page updates in your web application.
Lesson Objectives
After completing this lesson, you will be able to:
Partial page updates use AJAX technologies to help update individual sections of a webpage, during
postback. Partial page updates:
Question: How do partial page updates help in improving the responsiveness of a web application?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 09-3
An Example View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<div id="divMessage">@ViewBag.Message</div>
@Html.ActionLink("Refresh","HelloWorld")
</div>
</body>
</html>
In the preceding code example, ActionLink helps direct users to another view called HelloWorld.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>HelloWorld</title>
</head>
<body>
<div>
@ViewBag.Message
</div>
</body>
MCT USE ONLY. STUDENT USE PROHIBITED
09-4 Building Responsive Pages in ASP.NET MVC 5 Web Applications
</html>
To implement AJAX in the preceding code example, you need to update the HelloWorld view to render
only the content that is updated.
Consider another example wherein you want to render only an updated message, on a webpage. The
following code shows a view that is updated to render only the changed message.
A ViewBag Example
@ViewBag.Message
With AJAX, the Javascript retrieves only a specific portion of a webpage, which you want to update, from
the server. In the ViewController class, you need to update the View function to return the PartialView
class, instead of the entire View class.
The following code shows how to update the View function to return the PartialView class.
Optionally, you can add the HttpGet or HttpPost attributes before the View function. These attributes
help indicate if the partial page update should be performed over the HTTP POST or HTTP GET method.
Question: What is the mandatory action that you should perform to implement partial page updates in
your web application?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.js"
type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"
type="text/javascript"></script>
</head>
<body>
<div>
<div id="divMessage">@ViewBag.Message</div>
In the preceding example, parameters such as HttpMethod and UpdateTargetId are included along with
the Ajax.ActionLink helper, to:
• Obtain the HTML information from the HelloWorld view, by using the HTTP POST method.
Lesson 2
Implementing a Caching Strategy
Web applications display information on a webpage by retrieving the information from a database. If the
information that should be retrieved from the database is large, the application may take longer to
display the information on a webpage. ASP.NET MVC 5 supports some caching techniques to help reduce
the time required to process a user request.
Before implementing caching, you should first analyze if caching is relevant to your application, because
caching is irrelevant to webpages whose content change frequently. To successfully implement caching in
your web application, you need to familiarize yourself with the various types of caches, such as output
cache, data cache, and HTTP cache.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the benefits of using caching.
• Describe how to prevent caching for webpage content that changes frequently.
• Configure caching.
Caching:
• Reduces the need to reprocess data, if a user places a request multiple times.
• Helps improve the performance of a web application, by reducing the load on servers.
• Helps increase the number of users who can access the server farm.
However, caching does not help web applications that include frequent content changes. This is because,
the content rendered from a cache may be outdated, when compared to the current information.
Therefore, you should evaluate the content of your web application and analyze the impact of rendering
outdated content, before implementing caching.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 09-7
Question: How does caching help increase the scalability of a web application?
The OutputCache attribute helps direct the rendering engine to the cache that contains results from the
previous rendering process. The Duration parameter of the OutputCache attribute helps control the
period of time in seconds for which data should be stored in the cache.
By default, the output cache stores only one copy of the rendered content, for each view. Consider a view
with the QueryString input parameter that enables content to change based on the variable gathered
from the database or a prior request. In this case, you can add the VaryByParam property to the
OutputCache attribute, to store a copy of each unique combination of parameters in the cache.
The following code shows how to add the VaryByParam property to the OutputCache attribute.
In the preceding example, observe that the VaryByParam property refers to QueryString, instead of
other MVC parameters. You can also use the VaryByCustom property.
The following code shows how to add the VaryByCustom property to the OutputCache attribute.
Using VaryByCustom
[OutputCache(Duration = 60, VaryByCustom="browser")]
public PartialViewResult HelloWorld()
MCT USE ONLY. STUDENT USE PROHIBITED
09-8 Building Responsive Pages in ASP.NET MVC 5 Web Applications
{
ViewBag.Message = "Hello World";
return PartialView();
}
You can add browser as the input parameter to the VaryByCustom property. The browser parameter
helps store a copy of the rendered content corresponding to each browser that the application is run on.
If you want to control and implement your own logic to determine when a new copy should be stored,
you need to override the GetVaryByCustomString function in the Global.asax file of your project.
Question: How does the functioning of a web application that implements the output cache differ from
an application that does not implement output cache?
4. Ensuring that content is available in the MemoryCache object; otherwise, reloading the content
The following code shows how to add the MemoryCache object.
• Key. The unique identifier of the object that should be stored in the memory cache.
You can use the AddOrGetExisting function, instead of the Add function, to enable the application to
refresh and retrieve data in one line of code. If the cache contains the relevant data, the
AddOrGetExisting function retrieves the data from the cache. If the cache does not contain the relevant
data, the AddOrGetExisting function allows adding the data to the cache, and then rendering the same
data on the webpage.
Question: What are the benefits of implementing data caching in MVC applications?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 09-9
Question: What is the difference between HTTP cache and output cache?
Preventing Caching
Caching can sometimes create issues in web
applications, because if an application involves
frequent content updates, caching prevents users
from viewing these content updates. To resolve
caching issues, you can implement an HTTP
header called Cache-Control. The Cache-Control
header indicates to the web browser how to
handle the local cache. All HTTP clients, such as
browsers and proxy servers, respond to the
instructions provided in the Cache-Control header
to determine how to handle the local cache of a
web application.
Additional Reading: For more information about setting this header, go to:
http://go.microsoft.com/fwlink/?LinkID=288972&clcid=0x409
You can use the HttpCachePolicy.SetCacheability method to specify the value of the Cache-Control
header. The HttpCachePolicy.SetCacheability method helps control caching performance.
Using SetCacheability
Response.Cache.SetCacheability(HttpCacheability.Private);
MCT USE ONLY. STUDENT USE PROHIBITED
09-10 Building Responsive Pages in ASP.NET MVC 5 Web Applications
In the preceding example, the HttpCachePolicy.SetCacheability method takes the Private enumeration
value.
To prevent caching in your web application, you should set the Cache-Control header value to NoCache.
The code shows how to exclude the HTTP cache in your web application.
Preventing Caching
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Question: What scenarios would require you to prevent caching for a web application?
• Measure the difference that the configured cache makes to the delivery of the page.
Demonstration Steps
You will find the steps in the “Lesson 2: Implementing a Caching Strategy“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD09_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 09-11
You want to ensure that comments for photos take minimal loading time, for which you decide to use
partial page updates. You also want to return pages in quick time, while updated information is displayed,
for which you decide to configure caching in your application.
Objectives
After completing this lab, you will be able to:
• Write controller actions that can be called asynchronously and return partial views.
• Use common AJAX helpers to call asynchronous controller actions, and insert the results into Razor
views.
Lab Setup
Estimated Time: 70 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD09_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD09_LAK.md.
• Import a partially complete controller to add comments, and a view to delete comments.
• Add code to the controller for partial page update.
• Use the developer tools in Internet Explorer to examine the speed at which image files and pages
render with and without caching.
• Configure the output cache to store the results of the GetImage action so that image files can be
returned from the cache.
Complete this exercise if time permits.
Question: In Exercise 2, why was the Request timing for /Photo not reduced for the first
request when you configured the output cache for the index action?
Question: In Exercise 2, when you configured the output cache for the GetImage() action,
why was it necessary to set VaryByParam="id"?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 09-13
Review Question
Question: An application is refreshing the content every 10 seconds for the updated
information from database. User complaints that this is impacting their work and has caused
data loss. How would you propose to help resolve this issue?
Module 10
Using JavaScript and jQuery for Responsive MVC 5 Web
Applications
Contents:
Module Overview 10-1
Module Overview
Responsive web design is a web designing approach that helps create visually rich and interactive web
applications. JavaScript plays an important role in the development of responsive web applications. You
need to know how to use JavaScript to implement application logic and resize interface elements, without
triggering a full-page refresh. To simplify adding JavaScript to your web application, you need to know
how to use libraries such as jQuery, jQuery UI, and jQuery Mobile.
Objectives
After completing this module, you will be able to:
Lesson 1
Rendering and Executing JavaScript Code
You can create interactive HTML elements in your web application by using JavaScript. ASP.NET renders
these interactive elements on your webpages. You can add packaged JavaScript libraries to your project
by using the NuGet tool. You should know how to use AJAX to update the contents of webpages. By
using AJAX, you can optimize the performance of your web application. In addition, you should know
how the content delivery network (CDN) helps take content geographically closer to users.
Lesson Objectives
After completing this lesson, you will be able to:
If you have multiple HTML pages in a web application, you need to add JavaScript code for each HTML
page. You cannot simultaneously add JavaScript code for multiple HTML pages. Therefore, you can define
the JavaScript code in a JavaScript file (.js file). Then, you can reference the JavaScript file in multiple
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 10-3
HTML pages. This enables you to maintain a single JavaScript file, to edit the JavaScript code for multiple
HTML pages. You can also have multiple JavaScript code files for a single HTML page.
The following image displays the Add New Item dialog box that helps to add a JavaScript file.
You can create the Scripts folder in the root folder of your MVC project, and then save all JavaScript files
in the Scripts folder.
Before calling a JavaScript function, you need to define the function by using a script block. Then, you
must reference the JavaScript file from the HTML pages.
MCT USE ONLY. STUDENT USE PROHIBITED
10-4 Using JavaScript and jQuery for Responsive MVC 5 Web Applications
If you want to avoid calling the JavaScript function directly, you can use the onclick JavaScript event to
trigger JavaScript functions. The onclick event initiates the JavaScript function assigned to an HTML file,
when you click the corresponding HTML element. JavaScript functions that are attached to document
object model (DOM) events are called event handlers.
The following code shows how to add the HelloWorld event handler to the button’s onclick event.
Question: What is the advantage of initiating JavaScript functions by using JavaScript events?
JavaScript Libraries
You can reduce the time taken to develop
applications by using JavaScript libraries.
JavaScript libraries help to:
• jQuery (http://go.microsoft.com/fwlink/?LinkID=288974&clcid=0x409)
• jQuery UI (http://go.microsoft.com/fwlink/?LinkID=288975&clcid=0x410)
• Prototype (http://go.microsoft.com/fwlink/?LinkID=299651&clcid=0x409)
• MooTools (http://go.microsoft.com/fwlink/?LinkID=299652&clcid=0x409)
You can use JavaScript libraries to make your application more interactive. The functioning of JavaScript
codes depends on the version of the library you use. Not all code may work with all versions of a library.
The jQuery library (and its related libraries) has the additional advantage of dealing with the differences in
the DOM across different browsers and different browser versions.
Microsoft has a dedicated CDN called Microsoft Ajax CDN that hosts some popular JavaScript libraries,
such as:
• jQuery
• jQuery UI
• jQuery Mobile
• jQuery Validation
• jQuery Cycle
• jQuery DataTables
• ASP.NET Ajax
• ASP.NET MVC JavaScript Files
Note that Microsoft does not own the license of the JavaScript libraries mentioned in the preceding list.
Microsoft only hosts the libraries for developers.
You can often reduce the loading time of your web application, by using the JavaScript libraries hosted on
Microsoft Ajax CDN. Web browsers can cache these JavaScript libraries on a local system.
Question: How can CDN help improve the performance of a web application?
MCT USE ONLY. STUDENT USE PROHIBITED
10-6 Using JavaScript and jQuery for Responsive MVC 5 Web Applications
The following image shows the application page that you can use to manage NuGet packages.
Additional Reading: To search for NuGet packages and analyze the details of each
package, go to http://go.microsoft.com/fwlink/?LinkID=288981&clcid=0x410
Question: Why should you use NuGet packages to add JavaScript libraries to your web application?
Demonstration Steps
You will find the steps in the “Lesson 1: Rendering and Executing JavaScript Code“ section on the
following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD10_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
10-8 Using JavaScript and jQuery for Responsive MVC 5 Web Applications
Lesson 2
Using jQuery and jQueryUI
jQuery is a JavaScript library that simplifies the adding of JavaScript to HTML pages. jQuery is an open-
source software that you can use for free. It helps reduce the amount of code that you need to write, to
perform tasks such as accessing and modifying HTML elements on a webpage. You can use the ajax
function in jQuery to call a web service in your application. You can also use jQuery UI to add interactions,
animations, effects, and widgets to your web applications.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe jQuery.
• Describe how to link web applications to jQuery Libraries for client-side scripting.
Introduction to jQuery
jQuery is a JavaScript library that you can use with
different browsers. jQuery was first released in
2006. jQuery helps query the HTML Document
Object Model (DOM) and obtain a set of HTML
DOM elements. This feature of jQuery helps:
• Events
• Utilities
• Compatibility methods
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 10-9
• Multi-browser support
• jQuery UI. This library adds functions and other supporting elements that help implement a rich
interface to HTML-based applications.
• jQuery mobile. This library adds functions that optimize the application interface for mobile devices.
Question: Why should you use jQuery while developing web applications?
Referencing jQuery
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-3.2.1.min.js"
type="text/javascript"></script>
To use bundling and minification in your web application, you should perform the following steps:
BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
The ScriptBundle class enables you to define the bundle that helps combine multiple JavaScript libraries
into a single file. You can use a special placeholder, such as {version} in the JavaScript path, to help
update the version of jQuery libraries. ASP.NET replaces {version} with the latest version number of the
JavaScript libraries present in the Scripts folder. If the minified version of jQuery is available in the Scripts
folder, the MVC 5 engine selects the minified version for bundling. Then, in your View file, you can include
the following lines of code to render the bundled JavaScript file.
<head>
@Scripts.Render("~/bundles/jquery")
</head>
You should add the following line of code in a page or namespace of the Web.config file in the View
folder. This code helps trigger the functioning of @Scripts.Render.
<add namespace="System.Web.Optimization"/>
Based on the compilation setting in the Web.config file, the jQuery library renders minified versions of
Javascript. For example, the following code sets the debug attribute of the compilation element to false,
which allows jQuery to use the non-minified version of the libraries, making debugging of the libraries
easier.
Question: What are the benefits of using the minified version of jQuery in the production environment?
$(element name|#id|.class)
$(“#HelloButton”)
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 10-11
You can use jQuery to access or modify all instances of a specific HTML element, in an HTML page. The
following jQuery selector identifies all instances of the A element in an HTML page.
$(“a”)
After accessing the HTML elements, you can perform actions on the elements, such as:
The following example adds an event handler to the click event of the HelloButton HTML element.
If the jQuery scripts load before the webpage loads, you may encounter errors such as object not
defined. You can place the jQuery code in the document.ready event, to prevent the code from loading
until all HTML elements in the page load.
The following code shows how to use the document.ready function
The following complete example shows how to access HTML elements by using jQuery.
A Complete Example
<body>
<div>
Hello
<input type="button" value="Hello" id="HelloButton" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#HelloButton").click(function (event) {
alert("Hello World");
});
});
</script>
</body>
Question: Why should you include the jQuery code in the document.ready event?
MCT USE ONLY. STUDENT USE PROHIBITED
10-12 Using JavaScript and jQuery for Responsive MVC 5 Web Applications
You can use the css function to get or set the inline CSS style associated with an HTML element. The
following example shows how to use the css function to set the background color of an HTML element to
blue.
You can use the addclass function to assign a CSS class to an HTML element. The following example
shows how to use the addclass function to add the input_css_class to an HTML element.
Question: If querying HTML DOM returns multiple HTML elements, how will jQuery functions handle
these elements?
The ajax function uses the parameters type, datatype, url, data, contentType, success, and failure to
control how to call the web services. These parameters are described as follows:
• type. This parameter controls the request type that you should use while querying the web services.
• dataype. This parameter defines the data type to be sent for AJAX services.
• data. This parameter defines the data that you should provide as a parameter to the web services.
• contentType. This parameter defines the HTTP content type that you should use, when you submit
HTTP requests to web services.
• success. This parameter defines the name of the function, which will be triggered when the call
completes successfully.
• failure. This parameter defines the name of the function, which will be triggered when the call
completes with errors.
When calls to the web services complete, jQuery triggers one of two callback functions based on the
success of the call.
Introduction to jQueryUI
jQuery simplifies interacting with JavaScript
elements, by providing a simple query-based
syntax. jQuery UI is a library that includes widgets,
animations, and themes that help you to build a
rich user interface.
jQuery Widgets
You can add different types of widgets to your
pages by using the following jQuery functions:
• Accordion. This function adds accordion
containers to your webpage.
• Progressbar. This function adds animated and static progress bars to your webpage.
jQuery Effects
You can add various effects by using the following jQuery functions:
• Toggle Class, Add Class, Remove Class, and Switch Class. This function adds or removes CSS classes.
• Effect. This function adds a variety of effects, such as appear, slide-down, explode, and fade-in.
• Toggle. This function toggles any jQuery effect on and off.
• Hide and Show. This function displays or hides any jQuery effect.
jQuery Utility
You can align your webpage content by using the Position jQuery utility. This utility helps align an
element in relation to the position of another element.
To use jQuery UI:
Linking to jQuery UI
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.12.1/jquery-ui.min.js"
type="text/javascript"></script>
Question: What is the key difference between jQuery and jQuery UI?
Demonstration Steps
You will find the steps in the “Lesson 2: Using jQuery and jQueryUI“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD10_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 10-15
You want to use jQuery to create this slideshow because you want to cycle through the photos in the
browser, without reloading the page each time. You also want to animate slide transitions and show a
progress bar that illustrates the position of the current photo in the complete list. You will use jQueryUI to
generate the progress bar.
Begin by importing a partially complete view that will display all photos simultaneously in the correct
format. Then, change styles and add jQuery code to the application to create your slideshow.
Objectives
After completing this lab, you will be able to:
• Render and execute JavaScript code in the browser.
• Use the jQuery script library to update and animate page components.
Lab Setup
Estimated Time: 50 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD10_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD10_LAK.md.
• Import the view and modify the style sheet so that the photos are displayed on top of each other.
• Using jQuery, set the order for each photo so that each photo is displayed sequentially.
Question: What is the use of adding the two links to the _MainLayout.cshtml file in Task 1
of Exercise 2?
Question: You added <script> tags to the _MainTemplate.cshtml file to enable jQueryUI.
Is this the optimal location for this link?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 10-17
Review Question
Question: You are building an application that needs to update various parts of the page
every 10 seconds. Your team is proposing to use IFRAME. But you want to reduce the
number of pages to be created. What type of technology should you propose to achieve
this?
MCT USE ONLY. STUDENT USE PROHIBITED
10-18 Using JavaScript and jQuery for Responsive MVC 5 Web Applications
MCT USE ONLY. STUDENT USE PROHIBITED
11-1
Module 11
Controlling Access to ASP.NET MVC 5 Web Applications
Contents:
Module Overview 11-1
Module Overview
Authentication is a vital requirement in most web-based applications. Developers usually display only
restricted information to all users. Web applications require users to authenticate themselves to view
exclusive information. Web applications also display specific information that is relevant to specific user
roles. Microsoft ASP.NET includes various authentication models, including local authentication providers,
claim-based authentication systems, and federated authentication systems. You need to know how to use
these authentication models to implement authentication functionality in your web application. You
should also know how to authorize users and roles in your application to restrict information access
according to user and role membership.
Objectives
After completing this module, you will be able to:
• Implement authentication and authorization systems in your web application.
Lesson 1
Implementing Authentication and Authorization
Membership providers, which were introduced in ASP.NET 2.0, help you to create secure authentication
and authorizations systems for web applications. You need to know how to use the membership provider
model in ASP.NET, to change authentication methods with minimum changes to the code. You can use
claim-based authentication and federated authentication to allow external users to authenticate
themselves, and access and use the web application. You should know how to configure restrictions in the
web application to ensure that users access only specific information that is permitted and relevant to
them.
Lesson Objectives
After completing this lesson, you will be able to:
• List the local authentication options available for an ASP.NET web application.
• Describe how client-based authentication works.
The ASP.NET membership system allows application developers to switch amongst authentication
providers, without modifying the code.
• UniversalProviders. This is a set of membership providers that works with any database that Entity
Framework supports. However, these providers work only with the database schema designed by
Microsoft. While initializing a universal provider, if the schema does not exist in the database, the
provider generates the schema.
You can use ASP.NET Identity with ASP.NET frameworks, such as ASP.NET MVC, Web Forms, Web Pages,
Web API, and SignalR. You can use ASP.NET Identity when building web, phone, store, or hybrid
applications.
Question: What is the benefit of using SimpleMembershipProvider?
Claims-Based Authentication
Claims-based authentication is a model that
facilitates single sign-on. Single sign-on is a
feature that allows you to receive a claim when
you log on to a centralized authentication system.
The claim is a ticket that authentication systems
use to authenticate user logons. The claim
contains user identity information that helps
authentication systems identify users. With claims-
based authentication systems, you can focus
efforts on developing business functions, rather
than worrying about authenticating users.
• Integrating the application with the identity systems of other platforms or companies.
To implement claims-based authentication in your web application, you can use Windows Identity
Foundation (WIF). WIF is a set of .NET Framework classes that helps read information from the claims in a
web application.
2. The IP requires you to enter credentials such as the user name and password.
3. After you enter the credentials, the IP issues a token. Then, the token is returned to the web browser.
4. The web browser is redirected to the webpage that you originally requested. WIF determines if the
token satisfies the requirements to access the webpage. If the token satisfies all requirements, a
cookie is issued to establish a session. This cookie ensures that the authentication process occurs only
once. Then, the authentication control is passed on to the application.
ASP.NET Identity supports claims-based authentication. In ASP.NET Identity a set of claims represents the
user's identity.
Federated Authentication
Federations rely on claims-based authentication
to allow external parties such as trusted
companies to access their applications.
Federations use the WS-Federations claim
standard to enable the exchange of claims
between two parties in a standardized manner.
STS enables you to focus more on writing the business logic. It eliminates the need to manage the
authentication information of business partners, in your web application.
FederatedPassiveSignIn Control
Consider cases when unauthenticated users try to access protected resources and you want to redirect
these users to a logon page. For such cases, you can embed the FederatedPassiveSignIn control in the
logon page of your web application, to redirect unauthenticated users to the logon page. The
FederatedPassiveSignIn control is configured with issuer (STS) information.
Passive Redirect
Consider cases when unauthenticated users try to access a protected resource, and you want to redirect
these users to an STS without using an application logon page. For such cases, you can use passive
redirect.
• Issue security tokens that contain the appropriate claims for users.
You can instantiate WSFederationAuthenticationModule and use it to trigger the sign-on process. This
functionality is similar to that of the FederatedPassiveSignIn control; however, passive redirect
implements this sign-on functionality with minimum coding effort.
Observe the Authorize attribute in the code sample. If you specify this attribute, ASP.NET mandates that
users should be authorized to access the view returned by the code sample.
If you add the Authorize attribute at the class level, the attribute requires users to log on before they can
access anything in the controller class. To allow anonymous users to access a specific portion of your class,
you can use the AllowAnonymous attribute.
The following code shows how to use the AllowAnonymous attribute.
Question: Why should you use the Authorize attribute, instead of the Web.config file to control
authorization of pages in your ASP.NET MVC application?
Demonstration Steps
You will find the steps in the “Lesson 1: Implementing Authentication and Authorization“ section on the
following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD11_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 11-7
Lesson 2
Assigning Roles and Membership
Roles and memberships complement authentication features, to help you control all modes of access in
web applications. To define access levels for different types of users, you need to know how to implement
roles and users. ASP.NET provides role providers and membership providers to help you assign roles and
users. ASP.NET also enables you to create custom role providers and custom membership providers. These
custom providers allow you to store role and user information in data sources not supported by ASP.NET,
such as an Oracle database.
Lesson Objectives
After completing this lesson, you will be able to:
• Add code to an MVC 5 web application to help users reset their password.
• WindowsTokenRoleProvider. This provider uses the Windows authentication token to determine the
role of users. Then, the provider checks if users belong to any group stored in the Windows
authentication token that was generated when they first logged on. The format of the group name is
Domain\Group.
ActiveDirectoryRoleProvider and SqlRoleProvider have restrictions such as lack of support for non-SQL
databases or developer-defined schema. Therefore, Microsoft developed SimpleRoleProvider and
UniversalProviders to replace ActiveDirectoryRoleProvider and SqlRoleProvider. The following list
describes the SimpleRoleProvider and UniversalProviders:
MCT USE ONLY. STUDENT USE PROHIBITED
11-8 Controlling Access to ASP.NET MVC 5 Web Applications
• SimpleRoleProvider. This is a role provider that works with SQL Server, SQL Compact Editions, and
others versions of SQL Server. SimpleRoleProvider enables you to implement authorization based on
the table defined by application developers.
• UniversalProviders. This is a database agnostic version that works with any database that Entity
Framework supports. However, the database schema is determined by Microsoft. The provider usually
generates tables during initialization.
ASP.NET Identity contains a role provider that allows you to restrict access to the application using roles.
For example, you can create a role named Admin. You can easily create users in ASP.NET Identity and add
them to roles.
You can choose a role provider based on the membership provider that you select. You can also mix role
providers; for example, you can combine SimpleMembershipProvider and UniversalRoleProvider.
However, you should avoid mixing role providers because the manner in which each provider identifies
users is different.
You can also use the AddUsersToRoles function in business applications to add users to a role. However,
you must ensure that the role to which you want to add users exists, before using the AddUsersToRoles
function.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 11-9
In the RoleProvider class, you need to implement the GetRolesForUser function. The GetRolesForUser
function takes the user name as the input and returns a list of roles to which the user belongs. You can
write your own code to obtain role information from the database or other back-end stores.
The following code shows how to use the GetRolesForUser method.
After implementing the GetRolesForUser function, you need to apply the custom role provider to the
application by modifying the Web.config file.
The following code shows how to apply the custom role provider to the application.
Next, you need to create a User table. If you do not have a User table created already, you can modify the
AccountModel.cs file, to generate the table. To view the AccountModel.cs file, you should select the
Internet Application template, when you create the project.
In the following code sample, the UserProfile class from AccountModel.cs has been modified to add an
additional property, Country.
If a specific table does not exist in a database, the autoCreateTables parameter helps indicate to the
membership provider that it may create the table. To initialize SimpleMembershipProvider, you need to
add the InitializeSimpleMembership attribute to the AccountController class.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 11-11
The following code shows how to add the InitializeSimpleMembership attribute to the
AccountController class.
After implementing the custom membership provider, you override the ValidateUser method defined in
SimpleMembershipProvider. The following code shows how to override the ValidateUser method
defined in SimpleMembershipProvider.
In the preceding code sample, the ValidateUser method validates the user name and password against
the membership store.
Perhaps, you want to add logic to get the decryption key for passwords. To add this logic, you can
override the Provider constructor, when the custom membership provider is initializing. Overriding the
Provider constructor initializes the encryption engine.
After adding logic to the custom membership provider, you need to modify the Web.config file to apply
the custom provider class to the application.
<clear/>
<add name="CustomMemberProvider" type=" CustomAdminMembershipProvider " />
</providers>
</membership>
Demonstration Steps
You will find the steps in the “Lesson 2: Assigning Roles and Membership“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD11_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 11-13
You have been asked to resolve these concerns by creating a membership system for the Photo Sharing
application. Visitors should be able to register as users of the web application and create user accounts for
themselves. After registration, when the users sign in to the application, they will have access to actions
such as adding and deleting photos and comments. Anonymous users will not have access to perform
these actions. Additionally, registered users should also be able to reset their own password.
Objectives
After completing this lab, you will be able to:
• Configure a web application to use ASP.NET Form Authentication with accounts stored in Microsoft
Azure SQL database.
Lab Setup
Estimated Time: 90 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD11_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD11_LAK.md.
you need to build model classes, controllers, and views that enable users to sign in, sign out, and register
for an account.
• Add controllers.
• Only authenticated users see the_Create view for comments in the Display view.
Question: In Exercise 3, when you tried to add a photo before logging on to the
application, why did ASP.NET display the Login view?
Question: How can you ensure that only Adventure Works employees are granted
access to the Delete action of the Photo controller?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 11-15
Module 12
Building a Resilient ASP.NET MVC 5 Web Application
Contents:
Module Overview 12-1
Module Overview
Security is always the top priority for web applications, because publicly accessible web applications are
usually the targets of different types of web attacks. Hackers use web attacks to access sensitive
information. To help prevent these attacks, you need to know how to use AntiXSS and request validation
for your web application. Using various security mechanisms, you can build a secure web application.
Another problem that developers usually face is the need to retain information amongst multiple
postbacks. You need to know how to use state management techniques to retain information for multiple
HTTP requests. Using state management, you can help reduce the need for users to re-enter information
every time they need to place a request.
Objectives
After completing this module, you will be able to:
• Develop secure sites.
Lesson 1
Developing Secure Sites
Web applications are often subject to security attacks. These attacks prevent the applications from
functioning properly, and the attackers try to access sensitive information stored in the underlying data
store. ASP.NET provides built-in protection mechanisms that help prevent such attacks. However, such
mechanisms also tend to affect the operation of your applications. You should know when to enable or
disable the protection mechanisms to avoid any impact on the functionalities of your application. You also
need to know how to use Secure Sockets Layer (SSL) to prevent unauthorized access to information
during information transmission.
Lesson Objectives
After completing this lesson, you will be able to:
Cross-Site Scripting
Cross-site scripting involves the malicious
insertion of scripts in a user session. Cross-site
scripting poses information to other websites, by
using the authentication information of users,
without their knowledge. For example, consider
the code inserted into a web application to
maliciously post messages on social networking
websites, without the knowledge of the users.
When a script is inserted into a web application,
the script has full access to the Document Object
Model (DOM) of the HTML. This access allows the
attacker to create fake input boxes in the
application, create fake users, and post fake information on the web application.
The cross-site scripting attack usually takes input from improperly escaped output. These scripting attacks
usually impact query strings. For example, consider the following URL:
http://localhost/Default1/?msg=Hello
The following code shows how to access the msg querystring parameter from a controller action.
The following code shows how to display the value of the querystring parameter in a view.
After running the preceding code samples, the application should display the resultant word, Hello. Now,
consider a scenario where the query string parameter msg is changed to a less benign value resulting in
the following URL:
http://localhost/Default1/?msg=<script>alert('pwnd')</script>
As a result, the script block included in the query string is displayed to users. In such cases, attackers can
inject malicious code into your app by using the value of a query string parameter.
ASP.NET includes request validation, to help protect the input values that are subject to cross-site
scripting attacks. However, attackers can bypass this mechanism by using encoding to subvert common
cross-site scripting filters. For example, here is the same query string, this time encoded:
http://localhost/Default1/?msg=Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%20\x3c/script\x3e
You can modify the view class to use the @Ajax.JavaScriptStringEncode function to help prevent cross-
site scripting attacks, instead of directly using the input from query strings. The following line of code
shows how to use the @Ajax.JavaScriptStringEncode function.
You can also import the AntiXSS library to check the query string content for possible attacks. The AntiXSS
library is part of the Web Protection Library, which was developed by Microsoft to detect more complex
web attacks than those that the request validation of ASP.NET can detect.
After importing the AntiXSS library in your MVC application, you can use the library to encode any output
content in HTML.
The code in the preceding sample illustrates how to encode input values by using the JavaScriptEncode
method of the AntiXSS library, when displaying output in HTML. This practice ensures that the input
values are safe for display.
Question: What causes cross-site scripting attacks?
MCT USE ONLY. STUDENT USE PROHIBITED
12-4 Building a Resilient ASP.NET MVC 5 Web Application
3. Prevent any data modifications that use the GET request. These modifications should require some
user interaction. This practice of introducing user interaction does not help prevent form-based
attacks. However, user interaction limits several types of easier attacks, such as malicious links
embedded in XSS-compromised sites.
The @Html.AntiForgeryToken() function helps protect your system from CSRF by using unique tokens
that are passed to the application along with requests. The @Html.AntiForgeryToken() function uses
not only a hidden form field but also a cookie value, making it more difficult to forge a request.
The following code shows how to use the @Html.AntiForgeryToken() function in a view.
The following code shows how to force Anti-Forgery token checking in a controller by using the
ValidateAntiForgeryToken attribute.
Note the ValidateAntiForgeryToken() attribute in the preceding code sample. This attribute enables the
controller to check if the user input from the HTML form includes the token generated by the
@Html.AntiForgeryToken(), before accepting a request.
Consider a scenario where an attacker modifies the query string as displayed in the following line of code.
select userID from Users where userID = '1' AND 1=1 GO SELECT * from Users WHERE NOT
0=''
5. Ensure that the application does not use or access the database with administrator privileges.
Question: What is the best way to prevent SQL injection attacks if you cannot avoid dynamic SQL?
The following code shows how to add the ValidateInput(false) attribute to the controller, to disable
request validation for an action in a controller.
MCT USE ONLY. STUDENT USE PROHIBITED
12-6 Building a Resilient ASP.NET MVC 5 Web Application
The following code shows how to add the AllowHtml attribute to the Prop1 property of the model, to
disable request validation for this property
Question: Describe a scenario when you would want to disable request validation?
You can use SSL on views that accept user input if the input includes sensitive information, such as credit
card information and passwords. Using SSL on such crucial views ensures the confidentiality of the content
and the authenticity of the sender. However, you may not be able to analyze your code and easily detect
if a user accesses the web application by using SSL.
ASP.NET MVC 5 includes the RequireHttps attribute that enables you to use SSL on the views that involve
sensitive information. The RequireHttps attribute redirects users to the SSL link, if they request a view by
using normal HTTP.
The following code shows how to add the RequireHttps attribute in your controller class and action
methods to require a user to use the SSL protocol.
[RequireHttps]
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 12-7
You can use the RequireHttps attribute at the controller level or action level. This flexibility allows you to
choose SSL when required in your web application.
Note that web servers require you to configure the PKI certificate so that the server accepts SSL
connections. SSL certificates need to be purchased from a certificate authority (CA). During application
development, you can use the self-sign certificate to simplify the configuration process.
Question: What action is required to be performed on the web server, before implementing SSL?
MCT USE ONLY. STUDENT USE PROHIBITED
12-8 Building a Resilient ASP.NET MVC 5 Web Application
Lesson 2
State Management
While developing applications, you may want to create functions that require information to be retained
across requests. For example, consider an application in which you need to first select a customer and
then work on the order relevant to the customer. HTTP is a stateless protocol. Therefore, ASP.NET includes
different state management techniques to help store information for multiple HTTP requests. You need to
know how to configure and scale state storage mechanisms to support web server farms.
Lesson Objectives
After completing this lesson, you will be able to:
Session management enables web applications to store values for multiple HTTP requests, regardless of
whether the request is directed to the same page or multiple pages. The session management process
involves two techniques—server-side techniques and client-side techniques, to retain user information
pertinent to multiple HTTP requests.
• Cookies
• Query strings
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 12-9
Client-side session management technologies help retain dependent information when a user triggers the
HTTP POST action by clicking a button on a webpage. Then, when a page is rendered, the server
generates the dependent information.
Note: If you are familiar with ASP.NET Web Forms, you may have used View State and
Control State as client-side state storage. These techniques are not available in MVC because they
rely on Web Forms server controls.
• Session state
• TempData
• Profile properties
• Database support
• The SQLServer mode. Stores the session information in a SQL Server database.
• The Off mode. Deactivates the session state support in your application.
Question: Consider that you have a web server that contains multiple web servers. You want to allow
users to access the same state information for all the web servers they access. In this case, which state
storage mode should you used?
To configure an ASP.NET application for using the StateServer mode, you should perform the following
steps:
• In the Web.config file of the application, set the mode attribute of the sessionState element to
StateServer.
3. Open the Web.config file, identify the sessionState element, and then update the code.
Consider that a session state is stored on the SampleStateServer remote computer. The following code
shows how to configure the StateServer mode.
Note: The objects stored in session state must be serializable, if the mode is set to
StateServer or SQLServer.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 12-11
• In the Web.config file of the application, set the mode attribute of the sessionState element to
SQLServer.
• In the Web.config file of the application, set the sqlConnectionString attribute to a connection
string for your SQL Server database.
To create the session state database on SQL Server, you should perform the following steps:
1. Open the command prompt with administrative privileges.
3. Open the Web.config file, identify the sessionState element, and then update the code.
Consider that a session state is stored on the SampleSqlServer SQL Server. The following code shows
how to configure the SQLServer mode.
You can customize the behavior of the aspnet_regsql.exe tool by using switches such as -E, -S, and -d. You
can use these switches to change the name of the default ASPState database.
Additional Reading: For more information about the aspnet_regsql.exe tool, go to:
http://go.microsoft.com/fwlink/?LinkID=293693&clcid=0x409
Question: Which tool should you install before using the SQLServer mode?
management engine. Configuring the session management engine helps you use the logic to identify the
appropriate web server on which you can store information.
The following code shows how to configure the Web.config file, to enable the IPartitionResolver
interface.
You can use the IPartitionResolver interface only when the session state uses the SQLServer or
StateServer modes. In the preceding code sample, note that no connection string is specified by using the
sqlConnectionString or stateConnectionString attributes.
Question: When should you implement the IPartitionResolver interface?
Demonstration Steps
You will find the steps in the “Lesson 2: State Management“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD12_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 12-13
• Any visitor of the application, including anonymous users, should be able to mark a photograph as a
favorite.
• If a user has marked a favorite, a link should be available to display the favorite photo.
Objectives
After completing this lab, you will be able to:
• Store a setting for an anonymous or authenticated user in session state.
Lab Setup
Estimated Time: 35 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD12_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD12_LAK.md.
Question: In this lab, you stored the list of favorite photos in the session state. While
testing, your manager notices that authenticated users lose their favorite photos list
whenever they close their browser. Where would you store a list of favorites for each
authenticated user so that the list is preserved whenever a user logs on to the web
application?
Question: How would you create a view of favorite photos with the card-style
presentation users see on the All Photos page?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 12-15
Review Question
Question: Recently, an error occurred in one of applications that you had developed for
your company. After performing few tests, you realize that the issue was due to an HTML
code that was passed from the user to the server. You want to prevent such issues in the
future. What would you consider to do?
Complex business functions usually involve multiple views. Such functions can pose problems because
information must be shared across multiple views. Session state management helps resolve these
problems, because it enables retaining information pertinent to multiple views.
MCT USE ONLY. STUDENT USE PROHIBITED
12-16 Building a Resilient ASP.NET MVC 5 Web Application
MCT USE ONLY. STUDENT USE PROHIBITED
13-1
Module 13
Implementing Web APIs in ASP.NET MVC 5 Web
Applications
Contents:
Module Overview 13-1
Module Overview
Most web applications require integration with external systems such as mobile applications. You need to
know how to use Web APIs to promote application interaction with external systems. You can use the
Web API to implement Representational State Transfer (REST) services in your application. REST services
help reduce application overhead and limit the data that is transmitted between client and server systems.
You need to know how to call Web API services by using server-side code, jQuery code, and JSON.NET
library to effectively implement REST-style Web APIs in your application.
Objectives
After completing this module, you will be able to:
• Develop a Web API.
Lesson 1
Developing a Web API
You need to know how to develop Web API for applications, because Web API facilitates creating APIs for
mobile applications, desktop applications, web services, web applications, and other applications. By
creating a Web API, you make the information in your web application available for other developers to
use in their systems. Each web application has a different functional methodology; this difference can
cause interoperability issues in applications. REST services have a lightweight design, and Web API helps
implement REST services to solve the interoperability issues. You need to know how to use the different
routing methods that ASP.NET provides to implement REST services.
Lesson Objectives
After completing this lesson, you will be able to:
• Explain how to use routes and controllers to implement REST in Web APIs.
REST and Web API enable all kinds of different applications, including mobile device applications, to
interact with services. In particular, REST and Web API provide the following benefits for mobile
applications:
• They reduce the processing power needed to create complex request messages for data retrieval.
• They enhance the performance of the application by reducing the amount of data exchange between
client and server.
Question: What is the key benefit of using REST with Web APIs?
In the preceding code sample, observe that the default route includes the literal path segment api. This
segment ensures that Web API requests are clearly separate from MVC controller routes, because Web API
requests must start with api.
The first placeholder variable, {controller} helps identify the API controller to forward the request to. As for
MVC controllers, Web API appends the word, Controller, to this value to locate the right API controller
class. For example, Web API routes a request to the URI, api/products, to the controller called,
ProductsController. As for MVC controllers, the optional placeholder variable, {id}, is sent to the action as
a parameter.
You can also define your own API routes in the same manner as you do for MVC routes. Observe,
however, that Web API routes can handle requests from many types of client systems, including mobile
device applications, desktop applications, web applications, and web services. MVC routes only handle
web browser requests.
MCT USE ONLY. STUDENT USE PROHIBITED
13-4 Implementing Web APIs in ASP.NET MVC 5 Web Applications
Clients can make HTTP requests with one of four standard verbs: GET, POST, PUT, and DELETE. Other
verbs are possible. Web API looks for an action whose name begins with the requested HTTP verb. For
example, if the client sends a DELETE request to the URI api/products/23, Web API looks for a controller
called ProductsController. Within this controller, it locates an action whose name begins with Delete.
According to the default route, the segment 23 is the {id} parameter. If there is more than one action
whose name begins with Delete, Web API chooses the action that accepts a parameter called id.
HttpGet GET
HttpPut PUT
HttpPost POST
HttpDelete DELETE
The following code illustrates the use of the HttpGet attribute on the FindProduct action.
In the preceding code sample, observe that the HTTP attributes only allow mapping of one HTTP verb to
an action in the controller.
The following code shows the use of the AcceptVerbs attribute to map specific HTTP verbs to the action.
[AcceptVerbs("MKCOL")]
public void MakeCollection() { }
}
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 13-5
The following code shows how to map an action to an HTTP request by using a custom action name.
Mapping an Action
public class ProductsController : ApiController
{
[HttpGet]
[ActionName("Thumbnail")]
public HttpResponseMessage GetThumbnailImage(int id);
[HttpPost]
[ActionName("Thumbnail")]
public void AddThumbnailImage(int id);
}
1. In the New Project dialog box, click ASP.NET Web Application (.NET Framework).
2. In the New ASP.NET Web Application dialog box, click Web API.
The following image shows the New ASP.NET Web Application dialog box
The HTTP verb communicates to the Web API about the operations that it should perform; whereas, the
rest is to communicate which entity and operations to perform on. Therefore, HTTP plays an important
role. For example, consider the following API controller class.
In the preceding code sample, note the controller classes GetAllProducts and GetProductById. The
GetAllProducts controller class helps obtain a full list of products from the database. You can map the
following URL and HTTP verb with the GetAllProducts controller class.
GET /api/products
The GetProductById controller class helps obtain a specific product by using the ID detail. You can map
the following URL with the GetProductById controller class.
GET /api/products/id
Question: What is the syntax that the ASP.NET engine uses for mapping API controllers and action
functions?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 13-7
RESTful Services
REST uses URLs and HTTP verbs to uniquely
identify the entity that it operates on and the
action that it performs. REST helps retrieve
business information from the server. However, in
addition to data retrieval, business applications
perform more tasks such as creating, updating,
and deleting information on the database. Web
API and REST facilitate handling such additional
tasks. They use the HTTP method to identify the
operation that the application needs to perform.
GET Use this method with the following URL to obtain a list of all customers.
/api/customers
GET Use this method with the following URL to obtain a customer by using the
ID detail.
/api/customers/id
GET Use this method with the following URL to obtain customers by using the
category detail.
/api/customers?country=country
POST Use this method with the following URL to create a customer record.
/api/customers
PUT Use this method with the following URL to update a customer record.
/api/customers/id
DELETE Use this method with the following URL to delete a customer record.
/api/customers/id
MCT USE ONLY. STUDENT USE PROHIBITED
13-8 Implementing Web APIs in ASP.NET MVC 5 Web Applications
Web API allows developers to use a strong typed model for developers to manipulate HTTP request. The
following code shows how to use the POST, PUT, and DELETE methods for the create, update, and delete
requests to handle the creation, retrieval, updation, and deletion (CRUD) of the customer records.
CRUD Operations
public HttpResponseMessage PostCustomer(Customer item)
{
}
public void PutCustomer(int id, Customer item)
{
}
public void DeleteProduct(int id)
{
}
A JSON Response
{"Name":"Albert","Age":29,"Height":145,"Skills":["Programming", "Technical Writing"]}
You can represent the same data in the previous code sample, by using XML as shown in the following
code.
An XML Response
<Employee Name="Albert" Age="29" Height="145">
<Skills>
<Skill Name="Programming" />
<Skill Name="Technical Writing" />
</Skills>
</Employee>
When a client makes a request, the client can specify the data format for the response. If the data format
is not specified, Web API formats data as JSON by default.
Media Formatters
Web API uses a media formatter to format or serialize the information that a Web API REST service
returns. Web applications usually use the JSON format to format the data that functions return. However,
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 13-9
you can alternatively use the XML media formatter or add a custom media formatter to control the data
returned. Media formatters format the content that the server renders to the client systems.
For example, consider that you want Web API to return CSV files. In this case, you need to create a custom
media formatter, to create as output data files in the CSV format, instead of XML files in the JSON format.
The following code shows how to add a new class in your project, to create a custom media formatter.
Question: Why should you use a media formatter for Web API REST services?
Consider that you want to include multiple actions, such as creating customers with XML and JSON, in the
same HTTP method. In this case, you cannot use the default route because it requires a new request for
each HTTP method and URL combination. Therefore, you need to update the routing by modifying the
Route Map in the WebApiConfig class.
The following code shows how to update the routing, to support multiple operations in the same HTTP
method.
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
You can use the WebApiConfig class to enable multiple versions of API to coexist in the same project. For
example, you can include /api/v1/{controller} as Version One of your API and include
/api/v2/{controller} as a new version or Version Two of the API.
You may want to include supporting functions in the controller class, and hide the supporting functions
from the REST functions. You can eliminate the exposure of the function to the REST interface by adding
the NonAction attribute to the action function.
The following code shows how to add the NonAction attribute to the action function.
Using NonAction
[NonAction]
public string GetPrivateData()
{
By default, Web API exposes all public methods as REST services. You can prevent this by making the
function private, but this action prevents application code in the same project from accessing the
function. Therefore, you can use the NonAction attribute for functions that need to be in public, but do
not need to be exposed in REST.
Question: What is the key benefit of using the routing map?
Demonstration Steps
You will find the steps in the “Lesson 1: Developing a Web API“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD13_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 13-11
Lesson 2
Calling a Web API
After you complete the development of the Web API services, you need to create the client applications
to call these services. Calling Web API services is different from calling WCF services. However, the
methods that you need to use to call these services are similar, regardless of the platform. You need to
know how to call Web API services by using server-side code, jQuery code and JSON.NET library, to
effectively implement Web API services in most application platforms.
Lesson Objectives
After completing this lesson, you will be able to:
The last line of code in the preceding code sample informs the client system about the media type that
the client system should use. The default media type that applications use is application/json. However,
applications can use any other media type, based on the media type that the REST-style services support.
The following code shows how to call Web API REST services by using server-side code.
After running the code in the preceding code sample, you need to define a data model that aligns itself
with the one used by the Web API service to enable the .NET library to:
Then, you can use the GetAsync and ReadAsAsync methods to:
The PostAsJsonAsync function uses the HTTP POST method to call Web API services that support the
POST method.
In the preceding code sample, observe the dataType parameter of the ajax function. You should set this
parameter to json or another data type that the Web API service supports. Most applications use JSON
because it is light weight. The ajax function has built-in functionalities that parse JSON results for the ease
of developers.
You can use JSON.stringify() in the data parameter of the ajax function to serialize the JavaScript
objects into JSON objects for sending to the Web API method. The following code shows how to use
JSON.stringify() in the data parameter of the ajax function.
$.ajax({
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 13-13
url: 'http://localhost/api/customer',
type: 'POST',
data:JSON.stringify(customer),
contentType: "application/json;charset=utf-8",
success: function (data) {
},
error: function (x) {
}
});
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 60 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD13_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD13_LAK.md.
Question: How do the API actions you added to the PhotoApiController controller in
Exercise 1 differ from other actions in MVC controllers?
MCT USE ONLY. STUDENT USE PROHIBITED
13-16 Implementing Web APIs in ASP.NET MVC 5 Web Applications
REST services use HTTP methods such as GET, POST, and PUT to notify the API of the action that it needs
to perform. Web APIs use the media formatter and the JSON.NET library to serialize and deserialize
information, respectively. You can call Web API services by using server-side code, jQuery code, and the
JSON.NET library.
Review Question
Question: We are developing a mobile application, which requires to access business data
via internet. You are proposing to use Web API but your colleague is proposing to use WCF.
What would be the key point for using Web API in this scenario?
MCT USE ONLY. STUDENT USE PROHIBITED
14-1
Module 14
Handling Requests in ASP.NET MVC 5 Web Applications
Contents:
Module Overview 14-1
Module Overview
ASP.NET MVC provides functionalities that help develop web applications. However, ASP.NET MVC does
not include functionalities that help change the encoding of the output. In such cases, you need to know
how to use an HTTP module or HTTP handler, to facilitate such specific requests. Most web applications
require two-way communication between the client and server systems. The web sockets protocol
facilitates two-way communications in a robust manner.
Objectives
After completing this module, you will be able to:
• Use HTTP modules and HTTP handlers.
Lesson 1
Using HTTP Modules and HTTP Handlers
Applications perform actions on a request in the HTTP pipeline, before rendering a webpage. You need to
know how to use an HTTP module to implement custom authentication mechanism for a webpage,
before rendering the webpage. You can also use an HTTP module to create code that renders content in a
non-default encoding format that fits application needs. Sometimes, you may need the application to
handle requests by using application logic that differs from the built-in ASP.NET page rendering logic. In
such cases, you should know how to use the HTTP handler to process such specific requests.
Lesson Objectives
After completing this lesson, you will be able to:
• Security. Provide support for the custom authentication and authorization logic of your application
• Logging and statistics. Gather low-level information about the web application execution cycle, for
monitoring and logging purposes
• Custom headers and footers. Allow insertion of custom header information in the response of each
request
The following is a list of HTTP modules in ASP.NET:
• OutputCache
• Session
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 14-3
• WindowsAuthentication
• FormsAuthentication
• PassportAuthentication
• UrlAuthorization
• FileAuthorization
• DefaultAuthentication
If you configure HTTP modules in an application, HTTP modules apply to all the HTTP requests that the
application receives. You cannot configure an HTTP module for a specific page.
Question: What are the benefits of using HTTP modules in web applications?
In the CustomModule class, you need to implement the following two methods:
• ModuleName property. Provides a display name that enables other application code to identify the
HTTP module.
• Init function. Provides the location to implement all logic for an HTTP module. The HttpApplication
class triggers this function when the application receives a request.
The following code shows how to register an HTTP module for an application running in IIS.
</system.webServer>
</configuration>
Question: You have developed a custom HttpModule. What must you do to ensure that your ASP.NET
application uses the custom module developed?
• Web service handler (*.asmx). This is the default HTTP handler for web service pages.
• Generic web handler (*.ashx). This is the default HTTP handler for all web handlers that do not have a
user interface and include the @WebHandler directive.
• Trace handler (trace.axd). This is a handler that helps display page trace information.
You can use the *.ashx file extension with the Http handler because:
• The extension does not include any page-rendering logic.
• The extension allows developers to write logic to send responses to the client systems.
You can use a custom HTTP handler with the *.rss extension, to generate Real Simple Syndication (RSS)
feed content for user requests. You can also use a custom handler to request images from the database
and send the images to the client systems.
Question: What is the primary use of the HTTP generic handler (*.ashx)?
• You are creating a Representational State Transfer (REST)-based business application programming
interface (API) that requires a custom HTTP header, before accepting a request.
• You are creating a business API to provide content in custom XML format.
• You developing an application that requires saving diagnostic information about the header of an
HTTP request.
MCT USE ONLY. STUDENT USE PROHIBITED
14-6 Handling Requests in ASP.NET MVC 5 Web Applications
Lesson 2
Using Web Sockets
AJAX technologies are constantly evolving. The HTTP protocol does not cater to crucial requirements such
as real-time information updates from the server. You need to know how to use web sockets to create
two-way communication between the client and server systems. You also need to know when to use the
traditional HTTP model and the web sockets protocol, based on the needs of your application.
Lesson Objectives
After completing this lesson, you will be able to:
The web sockets work in a similar manner as traditional network sockets. The only difference is that during
the initial handshake, web sockets use the Upgrade HTTP request that includes the Upgrade HTTP
header. If the server accepts web sockets, the server returns a response with the status code, 101. Then,
the client and server systems send the payload by using the socket. When the client system no longer
requires communication with the server, the application sends a close connection payload, to notify the
server to close the web socket.
Question: What is the key difference between traditional HTTP and web sockets?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 14-7
What Is SignalR?
SignalR is a set of components that simplifies the
development of bidirectional real-time web
applications, such as chat rooms in websites.
SignalR uses WebSockets wherever possible to
connect. This means that it supports all HTML5
compatible browsers. A key advantage of using
SignalR is that it supports remote procedure calls
(RPCs) with HTML or even .NET applications and
can automatically switch to periodic polling for
older browsers.
After installation, you can implement the server-side code for the server logic.
To use SignalR, you need to implement a class that inherits from the Hub class. The following example
broadcasts a message to all clients when a message is received from one client.
Using SignalR
using Microsoft.AspNet.SignalR;
After implementing the server code, you must add the route to map the URL back the hub. The following
code defines a SignalR route using an OWIN startup class.
SignalR also includes a JavaScript library that can be used by clients to help perform communications
between client and server. The SignalR library depends on the jQuery library.
The following JavaScript code sends a message to the server, receives a message back, and displays the
received message.
$.connection.hub.start().done(function() {
$("#broadcast").click(function () {
chat.send(displayname, 'Hello');
});
});
});
</script>
Question: What is the key benefit of using SignalR, instead of WebSockets directly?
Demonstration Steps
You will find the steps in the “Lesson 2: Using Web Sockets“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD14_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 14-9
You have decided to use SignalR to implement the chat room over Web Sockets.
Objectives
After completing this lab, you will be able to:
• Install SignalR in an ASP.NET MVC 5 web application.
Lab Setup
Estimated Time: 60 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD14_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD14_LAK.md.
• Create a SignalR hub to accept messages from clients and forward those messages to other clients
who are chatting about the same photo.
• Create a new MVC controller action and Razor view to display the chat user interface for a particular
photo.
• Link to the JScript libraries that SignalR requires and write a client-side script to call the Join() and
Send() methods on the hub.
Question: In the chat functionality that you created, each photo in the Photo Sharing application
has a separate chat room. How is this separation possible with one SignalR hub?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 14-11
Review Question
Question: You want to select technology that could be used for developing a web based
chatting application for your client. Which technology would you prefer in this scenario?
MCT USE ONLY. STUDENT USE PROHIBITED
14-12 Handling Requests in ASP.NET MVC 5 Web Applications
MCT USE ONLY. STUDENT USE PROHIBITED
15-1
Module 15
Deploying ASP.NET MVC 5 Web Applications
Contents:
Module Overview 15-1
Module Overview
After developing an application, you need to deploy the application to the production environment to
make the application available to users. The configuration or deployment method of each application
varies based on the setup of the production environment. ASP.NET MVC applications have some special
considerations such as the configuration needed for IIS.
Objectives
After completing this module, you will be able to:
Lesson 1
Deploying a Web Application
The considerations for deploying a web application to a web farm are different for single and multi-server
configurations. For example, in multi-server web farms, you need to ensure that the state information is
available on all web servers. You also need to ensure that the dependencies needed for hosting ASP.NET
MVC 5 web applications are present in the web farm. If any of the application dependencies are missing
on the production web servers, some or all of your applications may not function and users may
encounter errors. You need to apply special considerations while deploying web applications on Microsoft
Azure. Deploying a web application on Microsoft Azure provides advantages such as high availability and
flexibility.
Lesson Objectives
After completing this lesson, you will be able to:
• Ensure that dependencies are present for hosting ASP.NET MVC4 applications.
• A Database server. Most web applications use a database to store information such as product details,
customer details, images, and other entities. You need to ensure that the production environment
supports the database that you used during development. For example, if you use SQL Compact
during development, you need to ensure that Microsoft SQL Compact is installed on the production
server. Alternatively, you can migrate the database to Microsoft SQL Server.
• Entity Framework. If you use Entity Framework to model data in your web application, you need to
ensure that you deploy the framework with your application.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 15-3
• Membership Providers. If your application uses membership providers to store user accounts and
roles, you need to ensure that these providers are available on the server. The .NET Framework
includes the SQL Server Membership Provider. If you use the Universal Membership Providers by
installing the NuGet package, you need to ensure that you include the NuGet package with your
deployed application.
Question: Which of the common requirements in the above list is required to support forms
authentication?
• Worker Process. The worker process uses a single execution process to run all the applications in a
pool.
• Memory. The applications share a single memory range, because the applications in a pool share a
single worker process.
The shared identity within an application pool affects the way the applications authenticate resources
such as database servers when using integrated authentication. Each application within a pool shares a
single user account. If each application has a separate database, you need to set permissions, to enable
the user accounts to access all the databases. If you separate applications into isolated pools, you can use
a different user account for each application. This practice can enhance the security of the application,
because each account can access only one database.
MCT USE ONLY. STUDENT USE PROHIBITED
15-4 Deploying ASP.NET MVC 5 Web Applications
If you decide to deploy your web application to a multi-server farm, you need to perform the following
steps. To complete these steps, you may need to work with the web server administrator who is
responsible for the server farm:
1. Create IIS applications and application pools on each server. This step is the same as configuring the
applications and application pools in a single-server scenario. However, you need to perform this step
on every server in the farm. You also need to ensure that applications and application pools have the
same configuration, throughout the farm.
2. Create a matching IIS configuration on each server. IIS configuration options, such as any encryption
certificates, file extensions, and optional components, should be identical on every server in the farm.
3. Use external hosted session state or session affinity. You can configure ASP.NET web applications to
store session state in the Windows State Service or a database. You should use this technique in a
multi-server farm, because each request from a single user session might be directed to a different
web server. Alternatively, by configuring session affinity, you can ensure that all requests from a user
session are always sent to the same web server. If you do not use external hosted session state or
session affinity, the user preference on one web server may get lost when a request is sent to another
web server. Session affinity is supported by some but not all load balancing solutions. Work with your
web server administrator to determine if affinity is available on your farm.
4. Configure the machineKey element in the Web.config file. If you are using external hosted session
state, you can encrypt the connection between the web servers and the State Service server or
database server. This technique improves security by protecting session state during network
transmissions. You can configure this encryption by setting up the machineKey element in the
Windows registry.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 15-5
Additional Reading: For more information about configuring the machineKey element,
go to: http://go.microsoft.com/fwlink/?LinkID=288995&clcid=0x424
Question: What is the purpose of configuring the machineKey element in the Web.config file?
3. Select Azure Web App and make sure you select “Use Existing”
4. Ensure that you select the correct connection strings for Entity Framework connections, service
database connections, and any other database connections.
5. Complete the Publish wizard.
6. Observe that Microsoft Visual Studio publishes the web application to Microsoft Azure.
When the process is complete, you can access the Microsoft Azure-hosted web application from any
Internet-connected browser.
Note: At the time of writing, Microsoft Azure web applications are still in preview, within
the Microsoft Azure platform.
Demonstration Steps
You will find the steps in the “Lesson 1: Deploying a Web Application“ section on the following page:
https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD15_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 15-7
Lesson 2
Deploying an ASP.NET MVC 5 Web Application
Deploying ASP.NET MVC applications is similar to deploying other ASP.NET applications. This process is
simple and straightforward. However, you need to update the configuration of the application for use in
the production environment. Microsoft Visual Studio includes features that simplify updating the
configuration of the application. You can also automate the deployment process by using deployment
tools available in Microsoft Visual Studio.
Lesson Objectives
After completing this lesson, you will be able to:
The following code shows how to remove the debug attribute from the Web.config file by using a
deployment transformation.
The following code shows how to remove the debug attribute from the Web.config file by using a
deployment transformation.
</system.web>
The preceding code sample uses the xdt:Transform attribute to modify the existing Web.config file and
produce the published Web.config file. You can also use the Insert value to add additional elements to
the resultant Web.config file.
For example, the following code shows how to insert a new connection string setting in the resultant
Web.config file.
Question: How can you configure the Web.config file for publishing to a production environment
without using the Web.release.config configuration file?
You can use the Add Deployable Dependencies feature to generate the _bin_deployableAssemblies
folder. This folder includes the following libraries:
• Microsoft.Web.Infrastructure
• System.Web.Helpers
• System.Web.Mvc
• System.Web.Razor
• System.Web.WebPages
• System.Web.WebPages.Deployment
• System.Web.WebPages.Razor
You can choose a specific set of libraries to include in Microsoft Visual Studio. This practice enables you to
ensure that Microsoft Visual Studio deploys the:
• Right assemblies.
You can then copy the library to the bin folder of the production server, after adding it to the library of
your project.
Question: Why should you use the deployable assembly as part of the deployment plan?
• File Share
• FTP
• Web Deploy
On the Publish web application page, you can
publish the application by using File Share or FTP.
You can use File Share for servers to which you have
direct network access. Alternatively, you can use File Share to publish a web application first to a local
folder. Then, you can manually copy the files to the web server. File Share also allows you to specify a
profile to store all deployment options. This practice eliminates the need to specify the deployment
options every time you publish the application.
If you select Web Deploy, you can specify database settings, such as connection strings, in the publishing
wizard. These settings will override the settings in the Web.config file in the target environment. Web
Deploy also includes tools to automatically update the schema of the database. These tools eliminate the
need to manually update the schema. The publishing tool detects all schema changes and generates
scripts to apply those changes to the published database. If your development and production web
servers are isolated from each other, you can run these generated scripts on the production environment.
This practice replicates schema changes on a server where Microsoft Visual Studio is not installed.
MCT USE ONLY. STUDENT USE PROHIBITED
15-10 Deploying ASP.NET MVC 5 Web Applications
Question: What is the benefit of using the Web Deploy publish tool?
Demonstration Steps
You will find the steps in the “Lesson 2: Deploying an ASP.NET MVC 5 Web Application “ section on the
following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD15_DEMO.md.
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 15-11
Objectives
After completing this lab, you will be able to:
Lab Setup
Estimated Time: 45 minutes
You will find the high-level steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD15_LAB_MANU
AL.md.
You will find the detailed steps on the following page: https://github.com/MicrosoftLearning/20486-
DevelopingASPNETMVCWebApplications/blob/master/Instructions/20486C/20486C_MOD15_LAK.md.
• Configure the Entity Framework initializer class, which fills the database with initial data, and ensure
that the build configuration and connection strings are correct.
• Create a new web application in Microsoft Azure and deploy the Photo Sharing application to the
new site.
Question: In the labs for this course, you used the same Microsoft Azure SQL Database
for both development and production. If you wanted to use separate databases for
development and production, but did not want to reconfigure the web application every
time you deployed to the development and production web servers, how would you
configure the web application?
MCT USE ONLY. STUDENT USE PROHIBITED
15-12 Deploying ASP.NET MVC 5 Web Applications
Visual Studio 2017 has a simple, yet powerful deployment tool that lets the developer to quickly and
safely deploy applications to Microsoft Azure Web Apps.
Review Question
Question: You need to create two packages for deployment-for testing and for production
environment. This is because of the difference in server name and other environment
settings. What should you do?
MCT USE ONLY. STUDENT USE PROHIBITED
Developing ASP.NET MVC 5 Web Applications 15-13
Course Evaluation
Keep this evaluation topic page if this is the final module in
this course. Insert the Product_Evaluation.ppt on this page.
If this is not the final module in the course, delete this page