building web applications with asp.net...
TRANSCRIPT
Building Web Applications With ASP.NET MVC
Course 977
977/CN/H.2/410/H.1
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
© LEARNING TREE INTERNATIONAL, INC.All rights reserved.
All trademarked product and company names are the property of their respective trademark holders.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, or translated into any language, without the prior written
permission of the publisher.
Copying software used in this course is prohibited without the express permission of Learning Tree International, Inc. Making unauthorized copies of
such software violates federal copyright law, which includes both civil and criminal penalties.
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The author would like to acknowledge the following for their contributionsto this course:
Stacy Diehl
Kevin Rattan
All the instructors who contribute with bug reporting and enhancement suggestions
Acknowledgments
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this course, you will
Build and deploy secure, scalable applications with ASP.NET MVC
Generate HTML dynamically with Razor view, partial views, and view helpers
Create a loosely coupled model with the Entity Framework and dependency injection
Develop application controllers and action filters
Structure applications with areas and URLs with routing
Build and validate forms with standard and custom HTML helpers
Design rich client and mobile UIs with Ajax, jQuery, and jQueryUI
Secure applications with authentication and third-party providers
Create RESTful services with web API
Course Objectives
API = application programming interface REST = representational UI = user interfaceHTML = hypertext markup language state transfer URL = uniform resource locator
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction and Overview
Chapter 1 Introducing ASP.NET MVC
Chapter 2 Views and the Razor View Engine
Chapter 3 The Model
Chapter 4 The Controller
Chapter 5 Forms and User Input
Chapter 6 Client-Side Features
Chapter 7 Building Professional Applications
Chapter 8 Application Deployment
Chapter 9 Course Summary
Course Evaluation
Appendix A Answers to Review Questions
Course Contents
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
This is an advanced class that assumes experience and familiarity with• .NET application development in C# or Visual Basic
– To the level of – Course 503, Visual Basic Programming for .NET, or– Course 419, C# Programming
• Object-oriented principles• Basic HTML skills
– Understanding of elements such as– <a>– <div>– <table>– <ul>
Inform your instructor if you don’t meet these prerequisites
Prerequisites
503419
®
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Can be done in either C# or VB
Many exercises have bonus sections• Have much less direction• Designed to apply what you learned
C:\977 folder• Contains starting points for each exercise• Contains incremental solutions for all
exercises
Other features• My Learning Tree
– All material and support to do the case studyat home
– A list of recommended books
Course Exercises
C# code
Finished exercises
Exercise starting point
VB code
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The exercises use Visual Studio 2013 and MVC 5• Most would work with previous versions of Visual Studio• MVC 3 or 4 could be used for most exercises
Additional software components installed using NuGet• Part of Visual Studio 2012+• Can be Installed on Visual Studio 2010 from Tools | Extensions and Updates
Required NuGet packages are in the C:\977 NuGet Packages folder
Software Used
© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Please feel free to ask questions at any time• If you are confused, you are probably not alone
Your instructor will be happy to answer all questions, provided that you allow the following responses:• “We’ll be discussing that later”• “I don’t know!”
– “But I’ll try to find out and get back to you”– “Does anyone in the room have experience with that?”
• “Let’s talk about that offline, at the break, or at lunch”
Be considerate of your classmates• Do not type on the keyboard while the instructor is lecturing• Turn off the ringer on mobile phones and pagers
Questions
Introducing ASP.NET MVC
Chapter 1
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Explore the MVC design pattern
Create a simple MVC application
Examine how the controller, the view, and the model interact
Introduce the main HTTP verbs
Compare ASP.NET Web Forms to MVC
Chapter Objectives
HTTP = Hypertext Transfer ProtocolMVC = Model View Controller
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The MVC Design Pattern MVC Workflow and Projects
The HTTP Protocol
Web Forms and MVC
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Applications are traditionally organized in at least three tiers or layers• Presentation: Manages the user interface• Business: The heart of the application where the business logic is applied• Data: Persistent storage management, usually in a relational database
MVC is a UI design pattern applied to web applications• Model: Represents the business and data tiers• View: Displays data to the user and handles user input• Controller: Logic that handles the flow of requests and responses between the
browser and the web server
ASP.NET MVC is the Microsoft implementation of the MVC design pattern• Provides views and controllers for the presentation tier• The model is the rest of the application and not part of ASP.NET MVC
– Can be used by other presentation layers, like WPF or mobile app
MVC and Multitier Applications
WPF = Windows Presentation Foundation
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
MVC and Multitier Applications
Presentation Business Data
Database
View
Controller Model
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Visual Studio 2013 promotes the convergence of ASP.NET infrastructures• Can mix Web Forms and MVC in same project• New Project dialog has only one choice: ASP.NET Web Application• Visual Studio 2012 templates are available in subsection
One ASP.NET
One ASP.NET – New in Visual Studio 2013
This section has templates from the previous version
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ASP.NET Project TemplatesASP.NET MVC application with some views
Empty ASP.NET project
Select frameworks to configure
Select authentication options
Add unit tests
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
This course is AdaptaLearn Enabled• Web technology has allowed us to produce “dynamic documents”
Steps and hints can be “folded” in and out to give increasing levels of detail, providing you with a tailored experience• Suitable to your personal background and work style• Answers to questions also can be folded and unfolded
AdaptaLearn also provides:• Simplified “copy and paste” of solution code
– Decreases need to search through files on the course load
• Internet links to other helpful information• Video playback for especially difficult actions• Ability to use outside of class for continued reference and practice
AdaptaLearn is easy to use• For your convenience, a paper copy of the Exercise Manual is also provided
– All detail levels are shown (hints and answers are unfolded)
AdaptaLearn™ Enabled
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo Now
Let’s try it now1. Launch AdaptaLearn by double-clicking its icon on the desktop2. Move the AdaptaLearn window to the side of your screen, or minimize it
so it is a thin strip across the top or bottom– Leave room for a work area for your development tools
3. Select the first exercise from the exercise menu4. Use <Ctrl><mouse_wheel> to change the font size as desired5. If your screen is small or you want to maximize the AdaptaLearn window,
use <Alt><Tab> to toggle back and forth6. A folded area is introduced in blue text
– Click the text to see how folds work7. A copy-and-paste area is in a blue box
– Hover over the box (but don’t click on it) and press <Ctrl><C>
Using AdaptaLearn™
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 1.1: Building a Simple MVC Application
Hands-On Exercise 1.1
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The MVC Design Pattern
MVC Workflow and Projects The HTTP Protocol
Web Forms and MVC
Chapter Contents
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The client makes a request by• Clicking a link• Posting a form• Making an Ajax call
In all cases, the request is routed to a method in a controller class• Called an action method
The controller calls the model• The model implements the business logic• The controller selects the view based on the return from the model
The view prepares the output• Mixing static and dynamic HTML
The controller returns the generated data to the client• Can also return other types of content, like images or JSON data
The Controller Is the Conductor
More on posting and Ajax in later chapters
JSON = JavaScript Object Notation
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
MVC Request and Response
Controller Model
View
21
3
45
6
Request
Response
The controller asks the model to process the request
The controller calls the view to generate the output
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Each controller is a class• Inherits from System.Web.Mvc.Controller• Action methods return ActionResult objects
URL includes the controller name and the action method• Controller name without the word Controller
Controller and Action Methods
public class HomeController : Controller{
public ActionResult Index(){
return View();}
}
http://server/Home/Index
The return view is named after the action method by default
C#
Public Class HomeControllerInherits System.Web.Mvc.ControllerFunction Index() As ActionResult
Return View()End Function
End Class
VB
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views contain HTML• Sent as-is to the browser• Can also include JavaScript that is run on the client, in the browser• Usually also include code that is run on the server to build dynamic HTML
A view engine transforms server-side code into HTML• Initial view engine was ASPX whose syntax is similar to that of Web Forms
– Code was entered in <% … %> blocks• MVC 3 added the Razor view engine
– Razor is used in all of the exercises• Non-Microsoft alternatives exist
Views and View Engines
ASPX = Active Server Page Extended File
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ASP.NET MVC uses naming conventions• Most can be changed or adapted• Easier to stick to the default conventions
The Controllers folder contains all controllers• Controller names end with the Controller suffix
The Models folder is just a placeholder • Business classes can be put there• They are often in a separate class library project
The Views folder has one subfolder foreach controller• Views are in a folder named after the controller
MVC Projects in Visual Studio
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The MVC Design Pattern
MVC Workflow and Projects
The HTTP Protocol Web Forms and MVC
Chapter Contents
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A simple request-response protocol• The client makes a request• The web server processes the request and sends a response to the client
The client is usually a web browser• Internet Explorer• Chrome• Firefox• Safari and others
Microsoft’s server is Internet Information Services (IIS)• On Windows server systems• Also on Windows workstations (XP, 7, 8 …), with a limited number of clients• Open-source alternatives exist
– Such as Mono (www.mono-project.com)
The HTTP Protocol
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The HTTP protocol is text-based• Requests and responses are made of a header and a body• The header is just plain text• The body is usually plain text, but can be in other formats
A request header starts with a verb• GET and POST request data from the server
– GET: Has no body; all data is sent as part of the URL– POST: Often used with forms; data is sent as the body of the request
The response body is usually HTML• Can also be XML or JSON data• Or an image, a video, a sound …
Fiddler is a free tool to trace HTTP requests and answers• Download from http://fiddler2.com/home• Major browsers also have developer tools that can display HTTP
– Press <F12> in browser
HTTP Verbs
XML = extensible markup language
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 1a: Exploring HTTP With Fiddler
1. Start Fiddler from its shortcut in the taskbar
2. Open the Do Now 1a starting point• This is the finished HelloMVC solution from the last exercise
3. Launch your application by pressing the <F5> key
4. Double-click the last HTTP request in the left pane of the Fiddler window
5. Click the Raw tab in both panes; in the bottom pane, click the yellow bar to decode the response
6. Explore the request header (it has no body) and the response header and body
7. Click one of the Time links and repeat the previous three steps
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowExploring HTTP With Fiddler Illustrated
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTTP request
HTTP response
HTTP Requests and Responses
A POST request would have some data in the body
Response code indicatessuccess or failure
Returned content data type
Returned data, displayed by the browser
GET verb with requested URL
Requested data type
User-Agent identifiesthe requesting browser
Blank line separatesheader from body
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The MVC Design Pattern
MVC Workflow and Projects
The HTTP Protocol
Web Forms and MVC
Chapter Contents
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ASP.NET has two technologies to develop web applications• ASP.NET Web Forms• ASP.NET MVC
ASP.NET Web Forms were part of .NET first release• Enhanced in each subsequent .NET version• Each HTML (.aspx) page has a code-behind file associated• Event handlers written in C# or Visual Basic
ASP.NET MVC was released out-of-band from Visual Studio• First version in 2009• MVC is open-source
– Source code can be downloaded from www.codeplex.com
Microsoft Technologies for Web Applications
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Web Forms use an event-driven architecture• Each user action in a page generates events on the server• Code in the code-behind intercepts and processes events• Same semantics as Windows Forms or WPF applications• A visual designer is available to design ASPX pages
ASP.NET MVC has no events• Each user action is routed to an action method in a controller• A routing table or routing attributes define the rules
ASP.NET MVC pros and cons• Pros
– Better structured– Full control of generated HTML– Easier to integrate with a TDD infrastructure
• Cons– No visual designer
ASP.NET Web Forms and MVC
TDD = test-driven development
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 1b: Designing Pages With No Designer1. Open the Do Now 1b starting point
• This is the finished HelloMVC solution from the last exercise
2. Press <Ctrl><F5> to start the application without debugging; organize the windows so that you see Visual Studio and Internet Explorer at the same time
3. Add some text to Index.cshtml in the Visual Studio HTML editor and save
4. Press <F5> in Internet Explorer to refresh the page
5. Close Internet Explorer
An alternative is the Visual Studio 2012+ Page Inspector
6. In Visual Studio, select Page Inspector in the toolbar and press <Ctrl><F5>
7. Add some text to the Index.cshtml file and save it
8. Refresh the Page Inspector to see changes
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoThe Course Case Study
Most exercises in the course will be based on a case study• A list management system• Lists can be of different types• Each list contains list items
Your instructor will demonstrate the ListPlus application• In C:\977\xx\Case Study\ListPlus
• Run the application and navigate to the My Lists menu• Explore the list and item display and edit
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we have
Explored the MVC design pattern
Created a simple MVC application
Examined how the controller, the view, and the model interact
Introduced the main HTTP verbs
Compared ASP.NET Web Forms to MVC
Chapter Summary
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 1-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
To which layer do the view and controller belong?
Name three Visual Studio templates for MVC applications
What is the role of the controller in an MVC application?
How are classes named in controllers?
Name some HTTP verbs
What are the main advantages of ASP.NET MVC over Web Forms?
Chapter Review
Views and the Razor View Engine
Chapter 2
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter Objectives
In this chapter, we will
Create views that display HTML data to the user
Build dynamic HTML using C# or VB code and Razor
Pass data from the controller to the view with the ViewBag and the model
Structure views with layouts and sections
Create reusable content with partial views and view helpers
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views, ViewBag, and Models
The Razor Syntax
Structuring Views With Layouts
Partial Views and View Helpers
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views
HTML files• Extension is cshtml (C#) or vbhtml (Visual Basic)• Mix of HTML elements and C# or VB code, using the Razor syntax
Can be full views or partial views• A full view is an HTML page displayed in the browser• A partial view can be included in a full view or other partial view
Can be shared between several controllers• Placed in the Views\Shared folder
Page layouts contain content that is common to several views• Header, footer, menu …
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller and the View
The action method in a controller selects the view to return• The View method causes the view to render• The view name defaults to the name of the action method
– Can be set explicitly as a parameter to the View method
• The following code has the same result
The view is located in a folder named after the controller• Views\Home for the Home controller
public ActionResult Index(){
return View();}
C# Function Index() As ActionResult
Return View()End Function
VB
public ActionResult Index(){
return View("Index");}
C# Function Index() As ActionResult
Return View("Index")End Function
VB
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Passing Data From the Controller to the View
Data can be passed in two ways• Though the ViewBag or the ViewData dictionary• As a parameter of the View method
Data is usually obtained from the model• Used inside the view to generate dynamic HTML
Controller Model
View
ViewBag is passed from controller to view
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The ViewBag
A dynamic data dictionary• Properties are created on the fly• Uses an Expando dynamic object• Create or update a property named Hello and set its value to World:
Wrapper around the ViewData dictionary• Same result as previous code snippet:
Using the ViewBag• In the controller
• In the view
ViewBag.Hello = "World";return View("Index");
C# ViewBag.Hello = "World"Return View("Index")
VB
ViewBag.Hello = "World"
ViewData["Hello"] = "World";C#
ViewData("Hello") = "World"VB
Hello @ViewBag.Hello Displays Hello World
C#
Razor
ViewBag.Hello = "World" VB
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Model
Classes designed to share data between the controller and the view• The controller instantiates a model class, or gets it from a service layer• Passes it to the view as a second parameter of the View method
The model’s class is available in the view through its Model property• By default, a dynamic (C#) or Object (VB) property• Not typed: IntelliSense won’t help during code editing
The view can be strongly typed• By adding a @model (C#) or @ModelType (VB) directive at the top of the file• The Model property has the type specified in
the directive
Visual Studio can help to create a strongly typed view• Select “Create a strongly typed view”
when adding a view• Select the model class in the list or type it
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The model classes are often properties-only classes
The action method gets the model and passes it to the view
Usually, the model is obtained from a call to a service layer• Or generated from classes retrieved from the service layer
Using the Model in the Controller
public class Person{
public int Id { get; set; }public string Name { get; set; }public int Age { get; set; }
}
C# Public Class Person
Property Id As IntegerProperty Name As StringProperty Age As Integer
End Class
VB
var person = new Person { Id = 1, Name = "Andrew", Age = 10 };return View(person);
C#
Dim thePerson As New Person With {.Id = 1, .Name = "Andrew", .Age = 10}Return View(thePerson)
VB
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoUsing the Model in the View The view uses the properties of the model
Add a directive at the top of the view to strongly type the model
Your instructor will demonstrate passing data between the controller and the view• Open the solution in C:\977\xx\Demo\Chapter 2\PassingData
Name: @Model.Name<br />Age: @Model.Age
@model ViewDemo.Models.PersonC#
@ModelType ViewDemo.PersonVB
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views, ViewBag, and Models
The Razor Syntax Structuring Views With Layouts
Partial Views and View Helpers
Chapter Contents
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Basic Razor Syntax Code is introduced with the @ character
• Text that follows is interpreted as C# or VB code by the Razor engine• Should return a value that will be sent to the output flow• A new line, a < character, and other special characters tell the Razor engine
to revert to plain text
• Resulting output if value of Name property is Andrew:
Name: @Model.Name<br />
Output as is in the HTML flow
Output as is in the HTML flow
Output of ToString()on the expression is sent to the HTML flow
Name: Andrew<br />
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Razor Expressions
Special characters can lead to unexpected results• For example:
• Output is:
A Razor expression can be put between parentheses• This syntax gives the expected result:
• Output:
Your age next year: @Model.Age+1
Your age next year: 10+1
Your age next year: @(Model.Age+1)
Your age next year: 11
Razor “thinks” expression is finished
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Loops and Tests C# and VB instructions can be used with the @ character
• for, foreach, while loops• If statements• LINQ expressions
Razor is usually smart enough to know where C# or VB starts and ends• Displaying a list of persons, if the model type is List<Person> (C#) or List(Of Person) (VB):
<ul>@foreach (var person in Model){
<li>@person.Name - @person.Age</li>}
</ul>
C#
<ul>@For Each person In Model
@<li>@person.Name - @person.Age</li>Next
</ul>
VB
C# switches back to HTML output
VB needs a hint with a @
Braces must be used in C#, even for one line instructions
LINQ = Language Integrated Query
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Code Blocks
Multiline code expressions can be entered with code blocks• @{...} in C#• @Code... End Code in VB• Previous code with a persons variable to name the model:
@{var persons = Model;
}<ul>
@foreach (var person in persons){
<li>@person.Name - @person.Age</li>}
</ul>
C#
@CodeDim persons = Model
End Code<ul>
@For Each person In persons@<li>@person.Name - @person.Age</li>
Next</ul>
VB
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
More Razor Syntax Comments are defined with @* … *@ blocks
• Can include Razor code or HTML, and be multiline• Comment blocks are not sent to the output page
To include some HTML in the output flow while in a Razor instruction• Use any HTML element, like <li> or <span>
• Or use @:
@foreach (var person in Model) {<span>Person name: @person.Name<br /></span>
}
C#
@For Each person In Model@<span>Person name: @person.Name<br /></span>
Next
VB
@foreach (var person in Model) {@:Person name: @person.Name<br />
}
C#
@For Each person In Model@:Person name: @person.Name<br />
Next
VB
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 2.1: Creating the Case Study Project
Hands-On Exercise 2.1
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views, ViewBag, and Models
The Razor Syntax
Structuring ViewsWith Layouts
Partial Views and View Helpers
Chapter Contents
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In most web applications, pages have a common layout• Header• Menu• Footer
Different areas in the application can have different layouts• Different design or content for public and private areas
Layout pages include HTML that is common to a set of pages• Similar to Web Forms master pages
Layout Pages
Header and menu, common to all pages
Content specific to this page
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Common markup belongs in a layout view• Specific markup stays in the view
Page-specific content is replaced by a placeholder in the layout view
Common HTML Markup
<!DOCTYPE html>
<html><head>
<meta name="viewport" content="width=device-width" /><title>Index</title>
</head><body>
<div>Hello Layout!
</div></body></html>
Common to all pages
Specific to this page
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The client requests the specific view• If the view defines the Layout property, the referenced layout is rendered• The body content is rendered with the @RenderBody placeholder
Layout and View
@{Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>Hello Layout!
</div> <!DOCTYPE html><html><head>
<meta name="viewport" content="width=device-width" /><title>Title</title>
</head><body>
@RenderBody()</body></html>
_Layout.cshtml
Index.cshtml
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
To avoid setting the Layout property in all views• Define it in a _ViewStart.xxhtml view, in the Views folder• In a view, set Layout to null or nothing to use no layout view
ViewStart
<div>Hello Layout!
</div> <!DOCTYPE html><html><head>
<meta name="viewport" content="width=device-width" /><title>Title</title>
</head><body>
@RenderBody()</body></html>
_Layout.cshtml
Index.cshtml
@{Layout = "~/Views/Shared/_Layout.cshtml";
}
_ViewStart.cshtml
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A layout view can have any number of section placeholders• Identified with a RenderSection method• Sections are defined in the view with a @section directive• The RenderBody method renders all the markup not inside a section
Layout Sections
<body>@RenderBody()
@RenderSection("footer", false)</body>
_Layout.cshtml
<div>Hello Layout!
</div>
@section footer{
<p>This is the footer</p>}
Index.cshtml
Section name
Section is not required
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
If a section is not marked as optional, it must be supplied in views• Otherwise an error is raised at runtime
Default HTML can be supplied in the layout view for optional sections• Using the IsSectionDefined method to find if section is defined in view
Section Default Value
<body>@RenderBody()
@RenderSection("footer", false)@if (!IsSectionDefined("footer")){
@:This is the footer from the layout}
</body>
_Layout.cshtml
Will only be rendered if footer section is not defined in view
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 2.2: Layout Pages
Hands-On Exercise 2.2
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Views, ViewBag, and Models
The Razor Syntax
Structuring Views With Layouts
Partial Views and View Helpers
Chapter Contents
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Parts of views can be reused in different ways• View helper methods are used within a single view• Partial views are view fragments that can be reused in different views• HTML helpers are methods that generate HTML
Factorizing Parts of Views
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
View helper methods are defined within a view• With a @helper Razor block• Defines a method that is local to the view• Can have parameters
View Helper Methods
@Display("Hello") ASP.NET @Display("MVC")
@helper Display(string text){
<b>@text</b>}
C#
@Display("Hello") ASP.NET @Display("MVC")
@helper Display(text As String)@<b>@text</b>
End helper
VB
C:\977\xx\Demo\Chapter 2\ViewHelper
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A partial view is a fragment of a view• Can be used in multiple views• Has HTML and code, like standard views• Can be strongly typed with its own model
To create a partial view• Right-click a view folder
and select Add View• Select the Create as partial view
checkbox• Can set a model in the dialog box
or using a @model directive
Place the view in the controller’s folder• Or the Views\Shared folder
to make it available for all views
Partial Views
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A partial view can be rendered anywhere in a view• With the Html.Partial method• Takes the name of the view as a parameter
To pass data from the main view to the partial view• Pass a model as the second parameter• Does not have to be the same model as the view• Can also pass a custom ViewData dictionary
Using a Partial View
This is the main view<br />Partial: @Html.Partial("Time", DateTime.Now)
Index.cshtml
Second parameter is the model
@model DateTime
The time is: @Model.ToShortTimeString()
Time.cshtml
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
An HTML helper is a method that returns a string containing HTML• Can be used in a view anywhere HTML can be used• ASP.NET MVC defines many HTML helpers• Can be extended with custom helpers
HTML helpers are defined in the HtmlHelper class• Accessed with the Html property in the view• ActionLink helper returns a link• The Encode method returns a string where special characters are encoded
– > is encoded as >• The Raw method returns the HTML without any transformation• Many more methods exist and are used extensively with forms
HTML Helpers
Forms and custom helpersare covered in Chapter 5
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The ActionLink HTML helper generates a link in a view• Produces a standard <a> element using information from the routing table• Several overloads can be used• In the Home controller
• Parameters are passed in an anonymous object
Generating Links in a View
@Html.ActionLink("Display", "Display")
<a href="/Home/Display">Display</a>
@Html.ActionLink("People list", “List", "People")
<a href="/People/List">People list</a>
@Html.ActionLink("Display", "Display", new { name = "Fred" })
<a href="/Home/Display?name=Fred">Display</a>
C:\977\xx\Demo\Chapter 2\Links
Routing is covered in Chapter 4
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 2.3: Styling and Simplifying the View
Hands-On Exercise 2.3
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A view is an instance of the WebViewPage class• A generic class typed to the model• Source code for the class is generated dynamically when view is requested
– Includes code to render the HTML elements– And the Razor code that is included in the page
The view is compiled when requested• Errors in the view don’t keep the application from running
– Although they are displayed in the error list during edit• Compilation errors are displayed at runtime in the browser• The developer must double-check and test views before deployment
The View Infrastructure
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The WebViewPage class has many properties• Can be found in the documentation at msdn.microsoft.com/library
WebViewPage Class
Property DescriptionContext HttpContext object associated with the page
App Applicationwide dynamic object; can be used to store and access properties across pages
Html HtmlHelper object used to render HTML elementsModel The model associated with a pageRequest, Response, Server, Session Give access to the corresponding ASP.NET objects
TempData A dictionary to store data during a requestUrl URL of the page
ViewBag, ViewData Dynamic object or dictionary to share data between the view and the controller
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter Summary
In this chapter, we have
Created views that display HTML data to the user
Built dynamic HTML using C# or VB code and Razor
Passed data from the controller to the view with the ViewBag and the model
Structured views with layouts and sections
Created reusable content with partial views and view helpers
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 2-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Name different ways to pass data from controller to view
Write a statement that sets the model type to Person in a view
How do you introduce a code block with Razor in C# or VB?
Name the command to render the body content in a layout view
Where would you set the name of the layout view in a project?
Which technologies help factorize parts of view?
Chapter Review
The Model
Chapter 3
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Build a solid architecture for the model
Implement a repository layer with the Entity Framework
Add a service layer to implement the business logic
Loosen the coupling between layers with dependency injection
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Model Tier Architecture Accessing Data With the Entity Framework
Repository and Data Query
Service and Business Logic
Decoupling Layers With Dependency Injection
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
When the user makes a request• Controller calls method(s) on the model• Model returns data• Controller passes data to the view• View builds the output to render in the browser
ASP.NET MVC has no support for the model• Just an empty folder in the project template!
ASP.NET MVC Architecture and the Model
Model
View
Request
Response Controller
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The model is the front end for business and data tiers• Holds the business logic and business rules• The business logic uses a data layer to store and retrieve data
The model comprises one or more classes• Can be in the MVC project or in a separate class library• All or part of the model can be on a different machine
– Accessed through web services such as WCF or web API
From Model to Database
Controller Business logic Data access Database
Model
View
WCF = Windows Communication Foundation
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Each layer in the model should do one and only one thing• Called Single Responsibility Principle (SRP) in design patterns• Each layer should also be as independent of other layers as possible
– Enables extensibility and evolution
Repositories give access to the database• Also called Data Access Layer (DAL) or Data Access Objects (DAO)
Services contain methods that are called by the controller• Get data from the repository and give it to the controller• Isolate the controller from the data access technology used
Layers in the Model
Repository DatabaseServiceController
View
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Passing data from database to controller involves two sets of classes• Entity classes are managed by the repository• View model classes are filled by the service
– Used by the controller and the view• Service transforms entities into view models and vice versa
This architecture has many advantages• Might be overkill for smaller projects
Data Classes
Repository DatabaseServiceController
Entity classesView model classes
View
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Model Tier Architecture
Accessing Data With the Entity Framework
Repository and Data Query
Service and Business Logic
Decoupling Layers With Dependency Injection
Chapter Contents
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Several technologies are available for data access• Pure ADO.NET code is the low-level technology for .NET• Dataset was Microsoft’s first tentative ORM for .NET Framework 1 and 2
Object-Relational Mapping (ORM) is a widely used technology• Library that maps relational data to classes• Several ORMs are available
– Entity Framework and LINQ to SQL are part of Visual Studio (VS)– Open-source alternatives such as nHibernate
.NET code and relational database mapping
Data Access Technologies
.NET code Relational databaseClass Table
Property ColumnObject Row
Collection Relation
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Entity Framework (EF) is Microsoft’s primary ORM• Now open-source, available on CodePlex• No longer part of the core .NET Framework• Can be added to a project with NuGet• Most MVC templates add Entity Framework to the project
Entity Framework can connect to different databases• SQL Server and its variations• Oracle or other DBMS with third-party drivers
Entity Framework
DBMS = database management system BI = Business Intelligence
SQL Server Edition DescriptionStandard, BI, Web, Enterprise Enterprise on premises
Express Free scaled-down editionAzure SQL Server in the cloud
LocalDB Included in VS for developmentCompact Embedded on devices
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Entity Framework can be used in three main modes• Database-first: Visual Studio EF designer generates classes from the
database schema• Model-first: The schema is created by the developer in the designer• Code-first: Existing classes are mapped to the database through attributes or
metadata classes• We’ll use database first in this course, to take advantage of the designer tools
Database-first• The Entity Framework designer generates classes from selected tables and
stored procedures• Also adds properties for primary key or foreign key relations
Entity Framework Modes
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 3.1: Adding Entity Framework to the Case Study
Hands-On Exercise 3.1
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Entity Framework designer reads the database schema from SQL Server• It generates an XML file with an edmx extension that describes the database,
the data model, and the mappings• It also generates T4 code files with the tt extension
The T4 code generator transforms the tt files into C# or VB classes • One entity class for each table or stored procedure return• A data adapter class that inherits from DbContext
– Generated code:
Entity Framework-Generated Files
public partial class ListPlusEntities : DbContextC#
Partial Public Class ListPlusEntitiesInherits DbContext
VB
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Model Tier Architecture
Accessing Data With the Entity Framework
Repository and Data Query Service and Business Logic
Decoupling Layers With Dependency Injection
Chapter Contents
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The basic database operations are done with the DbContext derived class • The DbContext derived class has a DbSet collection property for each entity• Can be queried with LINQ
To list all entities
CRUD Operations in the Repository
CRUD = Create, Retrieve, Update, Delete
public List<Listing> List(){
using (var db = new ListPlusEntities()){
return db.Listings.ToList();}
}
C#
Public Function List() As List(Of Listing)Using db = New ListPlusEntities
Return db.Listings.ToList()End Using
End Function
VB
Using block ensures DbContext is disposed
Derived class combines database name and Entities
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
SingleOrDefault returns a single entity
• If the criteria are the primary key, code can be simplified to
Reading a Single Entity
public Listing Read(int id){
using (var db = new ListPlusEntities()){
var q = from lst in db.Listings where lst.Id == id select lst;
return q.SingleOrDefault();}
}
C#
Public Function Read(id As Integer) As ListingUsing db = New ListPlusEntities
Dim q = From lst In db.ListingsWhere lst.Id = id Select lst
Return q.SingleOrDefault()End Using
End Function
VB
return db.Listings.Find(id);C#
Return db.Listings.Find(id)VB
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Modifications are done on the DbSet collections• And committed to the database with the SaveChanges method
To add a new item
Adding an Entity
public void Add(Listing listing){
using (var db = new ListPlusEntities()){
db.Listings.Add(listing);db.SaveChanges();
}}
C#
Public Sub Add(listing As Listing) Using db = New ListPlusEntities
db.Listings.Add(listing)db.SaveChanges()
End UsingEnd Sub
VB
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
To update an existing entity• Retrieve the entity • Change the modified properties• Save the changes
Or attach the entity• And set its state to modified
Updating an Entity
public void Update(Listing listing){
using (var db = new ListPlusEntities()){
db.Listings.Attach(listing);db.Entry(listing).State = EntityState.Modified;db.SaveChanges();
}}
C#
Public Sub Update(listing As Listing)Using db = New ListPlusEntities
db.Listings.Attach(listing)db.Entry(listing).State = EntityState.Modifieddb.SaveChanges()
End UsingEnd Sub
VB
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
To delete an existing entity• Retrieve the entity• Remove it from the entities collection• Save the changes
Deleting an Entity
public void Delete(Listing listing){
using (var db = new ListPlusEntities()){
var lst = db.Listings.Find(listing.Id);db.Listings.Remove(lst);db.SaveChanges();
}}
Public Sub Delete(listing As Listing)Using db = New ListPlusEntities
Dim lst = db.Listings.Find(listing.Id)db.Listings.Remove(lst)db.SaveChanges()
End UsingEnd Sub
VB
C#
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 3.2: Programming the Repository
Hands-On Exercise 3.2
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A layer should expose its functionality through interface(s)• If classes are exposed, the calling layer is dependent on the implementation• Using an interface helps separate the functionality from the implementation• Eases the move to a new implementation
– Like using nHibernate instead of Entity Framework
Loosely Coupled Applications
<<interface>>IListingRepository
ListAdd
UpdateDelete
ListingRepository
ListAdd
UpdateDelete
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Model Tier Architecture
Accessing Data With the Entity Framework
Repository and Data Query
Service and Business Logic Decoupling Layers With Dependency Injection
Chapter Contents
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The service layer is the core of the application• Has methods called by controllers• Fills view model classes that controllers and views use to display data• Implements the business logic of the application
The Service Layer
Repository DatabaseServiceController
Entity classesView model classes
View
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The data model is defined in the database with SQL code• Entity Framework manages the mapping between the data and entity models
The entity model is defined by Entity Framework• Or by the application if using code-first development
The view model is defined in the MVC application• The application code must map the entity model to the view model• Can be automated with software tools such as AutoMapper
Data, Entity, and View Models
Entity modelView model Data model
MVC application Entity Framework Database
Entity Framework
Application code
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
View model classes are often similar to entity classes• Have the same properties as the entity• Can have additional properties• Can combine data from multiple entities
The MVC developer shapes the view model classes as needed• Only used by the controllers and the views• The entity classes are often defined in sealed class libraries
Mapping between view model and entity classes can be automated• With a library like AutoMapper• Free, added to a project via a NuGet package• Properties are mapped by name by default• Mapping can be customized for each property• See automapper.org for more information
View Model Classes
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The service layer should expose its functionality through interfaces• Just like the repository layer• Necessary for implementing dependency injection
Steps to retrieve data1. The controller calls a method in the service2. Service calls one or more methods in the repository3. Repository methods use Entity Framework to get data from the database4. Repository returns entities to the service5. Service implements the business rules and processes the returned entities6. Service builds a view model and returns it to the controller7. Controller selects the view and passes the view model to the view8. The view uses the view model to build HTML
Service Classes and Interfaces
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The service layer “knows” both the view models and the entities• The controllers and views only “know” the view models• The repository only “knows” the entities• This is implemented in the solution with project references
Project References
Service Repository
View models
Controllersviews
Entities
Reference
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 3.3: Adding the Service Layer
Hands-On Exercise 3.3
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Model Tier Architecture
Accessing Data With the Entity Framework
Repository and Data Query
Service and Business Logic
Decoupling Layers With Dependency Injection
Chapter Contents
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The layers in the case study architecture are tightly coupled• The controller creates an instance of the service and has to know the
concrete class that implements the service
• Likewise, the service creates an instance of the repository
Replacing one layer would require modifying the whole application• For example, replacing the repository with an nHibernate implementation
Tight Coupling
_listingService = new ListingService();
_listingService = New ListingService()VB
C#
_listingRepository = new ListingRepository();
_listingRepository = New ListingRepository()VB
C#
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Dependency Injection (DI) or Inversion of Control (IoC) is a design pattern• Loose coupling of components• A component is referred to by its interface• The concrete implementation is injected at runtime
A DI container is a broker between the dependent components• Interfaces and their concrete implementations are registered in the container• When an interface is required, the container finds and supplies a concrete
implementation, i.e., an object• Implementation is often injected in constructors• Configuration can be done in XML or with code
There are many DI containers available, such as• Ninject• Unity• StructureMap• Spring.NET• And more
Loose Coupling With Dependency Injection
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The case study project uses Ninject• Free• Simple to configure• Simple to use
To use Ninject in a project, it must be installed• Easily done with NuGet• Adds a reference to the Ninject DLL
To configure Ninject• Define a dependency resolver class that implements the IDependencyResolver interface– Most code is added automatically to the project– Only bindings need to be customized
• Register that dependency resolver with MVC
Using Ninject
DLL = dynamic link library
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Dependency Resolver (C#)
public class NinjectConfig : IDependencyResolver{
private readonly IKernel _kernel;
public NinjectConfig(){
_kernel = new StandardKernel();
_kernel.Bind<IListingService>().To<ListingService>();_kernel.Bind<IListingItemService>().To<ListingItemService>();
}
public object GetService(Type serviceType){
return _kernel.TryGet(serviceType);}
public IEnumerable<object> GetServices(Type serviceType){
return _kernel.GetAll(serviceType);}
}
C#
Ninject kernel
Binding interfaces to classes
Called by the MVC infrastructure when a concrete type is required
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Dependency Resolver (VB)
Public Class NinjectConfigImplements IDependencyResolver
Private ReadOnly _kernel As IKernel
Public Sub New()_kernel = New StandardKernel()
_kernel.Bind(Of IListingService)().To(Of ListingService)()_kernel.Bind(Of IListingItemService)().To(Of ListingItemService)()
End Sub
Public Function GetService(serviceType As Type) As Object _Implements IDependencyResolver.GetService
Return _kernel.TryGet(serviceType)End Function
Public Function GetServices(serviceType As Type) _As IEnumerable(Of Object) Implements IDependencyResolver.GetServicesReturn _kernel.GetAll(serviceType)
End FunctionEnd Class
VB
Ninject kernelBinding interfaces to classes
Called by the MVC infrastructure when a concrete type is required
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Typically done in global.asax• Application_Start method called when the application starts• Call static SetResolver method of the MVC DependencyResolver class
When a controller is required• MVC will call the GetService method of our dependency resolver• Ninject kernel gets the controller from its name and looks at its constructor• Ninject instantiates the concrete classes bound to the required interfaces
– Passes them as parameters to the controller’s constructor
Registering the Dependency Resolver
DependencyResolver.SetResolver(new NinjectConfig());
DependencyResolver.SetResolver(New NinjectConfig())VB
C#
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toOptional Hands-On Exercise 3.4: Adding the Ninject DI Container
Optional Hands-On Exercise 3.4
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we have
Built a solid architecture for the model
Implemented a repository layer with the Entity Framework
Added a service layer to implement the business logic
Loosened the coupling between layers with dependency injection
Chapter Summary
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 3-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
What is the role of the model in the MVC architecture?
Name layers that help structure the model
Which class is the entry point to access data with the Entity Framework?
How would you break dependencies between layers in the model?
To which code element are these database items mapped with an ORM?
Chapter Review
TableColumn
RowRelation
The Controller
Chapter 4
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Create controllers with the Controller class
Write action methods with parameters
Examine the different types of action results
Write and use filters
Customize route tables
Structure applications with areas
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller Class Action Methods and ActionResult
Filters
Routing
Areas
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The controller receives requests from the client• Asks the model to do the processing• Selects the view to build the response
The Controller Is the Conductor
Model
View
Request
Response Controller
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Implements the IController interface• Custom controllers usually derive from the Controller class
The Controller class has many properties• Some of them are shown below
Controller-derived classes contain action methods• Called when requests are made from the browser
The Controller Class
Property DescriptionHttpContext HTTP-specific information about the HTTP requestRequest Contains data about the requestResponse Used to add data to the responseRouteData Route data for the current requestSession ASP.NET session objectTempData Dictionary used to store data from one request to the next
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ViewData, TempData, and Session are dictionaries• Key is a string, value is an object• Can store any type of data
ViewData only lasts for the duration of a request• Can also be accessed through the ViewBag
TempData is used to pass data from one request to the next• Data is removed from dictionary when read• First request sets the data, next request reads it―which destroys it
Session data lasts for the duration of a session• By default, 20 minutes without a request• Can be changed in Web.config, in <sessionState> element• Session can also be closed by code with Session.Abandon()
Storing Data on the Server
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Setting data in TempData or Session
Getting data from TempData or Session
Storing Data on the Server—Illustrated
TempData["name"] = "foo";orSession["name"] = "foo";
C#
var nameTemp = TempData["name"];orvar nameSession = Session["name"];
C#
TempData("name") = "foo"orSession("name") = "foo"
Dim nameTemp = TempData("name")orDim nameSession = Session("name")
VB
VB
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller Class
Action Methods and ActionResult
Filters
Routing
Areas
Chapter Contents
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A controller can have several action methods• Each action method corresponds to a specific URL• Defined by the application’s routing rules
An action method returns an ActionResult• Base class has just one method: ExecuteResult• ExecuteResult generates the output and puts it in the response
Action Methods
http://localhost:1234/Listing/List
public class ListingController : Controller{
public ActionResult List(){
return View();}
}
Routing is covered later in this chapter
C#
Public Class ListingControllerInherits System.Web.Mvc.Controller
Function List() As ActionResultReturn View()
End FunctionEnd Class
VB
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
An action method can have parameters• Data can come from the query string (URL parameters) or form data• Query string and form data are mapped to parameters by name• Binding can map to individual types, collections, or classes
If parameter is not supplied on query string or form, a null value is passed• Raises an exception for value types (numbers, dates …)• Can make parameter nullable or set a default value
Action Method Parameters
Forms and form dataare covered later
http://localhost:1234/ListingItem/List?listingId=12
public ActionResult List(int listingId){
return View();}
C#
Function List(listingId As Integer) As ActionResultReturn View()
End Function
VB
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The type of an action method parameter can be a class or structure• Mapping is done from source data to each property• Not case-sensitive• Properties that do not have source data will be null
Mapping Parameters to Complex Data
public string Display2(Person person){}
C#
http://localhost:1234/Simple/Display2?Name=Fred&Age=12
public class Person{
public string Name { get; set; }public int? Age { get; set; }
}
Public Function Display2(person As Person)
End Function
VB
Public Class PersonProperty Name As StringProperty Age As Integer?
End Class
Person.Name is FredPerson.Age is 12
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 4a: Action Method Parameters1. Open the Do Now 4a starting point and run the application
• The controller and action method names should be displayed
2. Add ?name=Hello at the end of the URL, after the / character
• What is displayed in the browser?
3. Test with the ?name=Hello&age=10 at the end of the URL
4. Add a second parameter age of type integer to the Index method in the Home controller, and modify the code to display the age
• What happens if you omit the age parameter in the URL?
5. Fix the issue by defining the age parameter as a nullable integer, or by setting a default value, then test
6. Use the Person class as the unique parameter to the Display method, adjust the code to use that class, and test again
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
An action method returns an ActionResult object• Or a null value• After the action method has returned, the ASP.NET MVC framework calls ExecuteResult on the ActionResult object
ActionResult is an abstract base class• Several derived concrete classes are part of MVC• Can create custom ActionResult-derived class
Each ActionResult-derived class can choose how to process the result• Generally putting some data in the HTTP response
The controller class has helper methods to generate specific action results• For example, View to return a ViewResult object
ActionResult
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ActionResult Classes
Class Controller Method Description
ViewResult View Return HTML defined in xxhtml view
PartialViewResult PartialView Return HTML defined in partial view
RedirectResult Redirect Redirect to a URL
RedirectToRouteResult RedirectToRoute Redirect to a URL using route data
FileResult File Base class for classes that return file data
ContentResult Content Put a string in the responseJsonResult Json Return some JSON dataEmptyResult null Does not return anything
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller Class
Action Methods and ActionResult
Filters Routing
Areas
Chapter Contents
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
1. The routing module analyzes the URL and builds a RouteData• Contains controller name, action name, and parameters• It uses the route table to map URL elements to RouteData members
2. The RouteData object is passed to the controller factory• The controller factory searches for the controller class using the name in the RouteData object, and instantiates it
3. The controller calls the action invoker, passing it the action name• The action invoker finds the action and invokes it
4. The action method asks the model to do the processing and prepares the ActionResult
• Usually a view• Can also be text, an image, some JSON data, a redirect instruction …
5. The ExecuteResult method of the ActionResult is called• For a view, builds the response that is sent back to the client• Other types act accordingly
Processing a Request in an MVC Application
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
From Request to Response
Routing
ControllerFactory
Controller
Action Invoker
Action Method
Request
Response
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Attributes are .NET classes that inherit from the Attribute class• Name usually ends with Attribute• Can be used with or without the Attribute suffix• Applied to classes, interfaces, properties, methods, parameters …• Queried by the compiler, the MVC framework, a custom application
Filters are attributes that can be set on action methods or controllers• If set on a controller, applies to all action methods in the controller• Can also be set for all controllers in global.asax
MVC filters derive from the FilterAttribute class• MVC defines some built-in filters• Custom action filters derive from the ActionFilterAttribute class
Attributes and MVC Filters
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Main built-in filters
Built-In Filters
Filter attribute DescriptionAuthorize Authorize caller to execute action methodHandleError Process unhandled exceptionsRequireHttps Require/redirects to HTTPS to call actionValidateInputValidateAntiForgeryToken Apply security to user input
ChildActionOnlyAction can only be called from the Action or RenderAction helper methods
OutputCache Caching action method output
Most built-in filters are covered in other chapters, where relevant
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
MVC defines two types of filters• Action filters are executed before and after an action method• Result filters are executed before and after processing the result
Custom action filters can also be defined• Implementing the IActionFilter and/or IResultFilter interfaces• Or in a class that derives from ActionFilterAttribute
Action and Result Filters
Controller
Action method
ActionResult
Before action filter
MVC framework
After action filter
Before result filter
After result filter
1
2
3
4
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ActionFilterAttribute implements both IActionFilter and IResultFilter interfaces• To use, define a class that derives from ActionFilterAttribute• Has four overridable methods
Custom Action Filter
Method DescriptionOnActionExecuting Called before an action method is executedOnActionExecuted Called after an action method is executed
OnResultExecuting Called before the ExecuteResult methodis executed on an action result
OnResultExecuted Called after the ExecuteResult method is executed on an action result
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 4b: Profiling With Action Filters1. Open the Do Now 4b starting point
2. Open the ProfileFilterAttribute class in the Filters folder• It starts a stopwatch when action begins, and stops it at the end
3. Open the Home controller; add a ProfileFilter attribute to the Indexmethod• C# code: [ProfileFilter] • VB code: <ProfileFilter>
4. Add a call to System.Threading.Thread.Sleep before returning the view; set a sleep time of 500 milliseconds
5. Run the application with <F5> and look in the Visual Studio Output window when you refresh the Index page• The displayed value should be close to 500
6. If you have more time: Look at the solution in the completed folder for an example of a result filter
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Caches the output of an action method• Using ASP.NET caching infrastructure• On first call to the action method, execution runs normally• Subsequent calls return the cached output
Using an output cache can enhance performance• However, output does not reflect current state of data• Not appropriate where data changes frequently
Duration property specifies number of seconds to cache• Next request after expiration will execute the action method code again• Other properties can fine-tune the way the cache works
OutputCache Attribute
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Main properties of the OutputCache attribute
OutputCache Attribute Properties
Property DescriptionDuration Time in seconds before the cache expires
VaryByParamSemicolon-separated list of GET or POST values that will cause distinct copies to be cached; if *, all variations will be cached separately
LocationLocation where the cache is stored; can be Server, Client, Downstream (client or proxies), ServerAndClient, Any, or None
CacheProfileUse settings from the OutputCacheSettings in Web.config
SqlDependency Use the ASP.NET/SQL Server cache dependency feature
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 4.1: Caching Action Method Output
Hands-On Exercise 4.1
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller Class
Action Methods and ActionResult
Filters
Routing Areas
Chapter Contents
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Maps incoming URLs to action methods in controllers• Also processes parameters• Known as incoming or inbound routing
Also generates URLs from controller and action names• Including parameters• Known as outgoing or outbound routing
Incoming routing is the first processing done on a request• The requested URL is analyzed• The controller and action names are extracted
Two strategies to define routes• Convention-based routing
– Uses a route table initialized at application startup• Attribute routing (new in MVC 5)• Both can be used in the same application
Routing
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
URLs are often directly mapped to the folder structure of the website
• Could map to
• URLs can also have parameters
Ugly URLs• Difficult to remember• Prone to changes, making bookmarks unreliable• Can reveal underlying architecture
Routing removes direct link between URL and physical structure• Gives the developer complete control of the URL• Short URLs, easy to type• Less subject to changes• Search Engine Optimization (SEO)
– Search engines give a greater weight to words in the URL
Why Routing?
http://www.server.com/admin/pages/index.html
C:\wwwroot\accounting\admin\pages\index.html
http://www.server.com/admin/pages/index.html?id=567h98gf-66&opt=password
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Routing rules apply to URL segments after the server name
A route table defines a URL pattern• Mapped to the slash-separated URL segments• Named segments are between curly braces
• With this URL and this pattern– The route value controller will be ListingItem– The route value action will be ItemList– The route value id will be 1
URL Structure and Route Patterns
http://www.server.com/Home/Index
Segment 1 Segment 2Protocol Server
{controller}/{action}/{id}
http://www.server.com/ListingItem/ItemList/1
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Route segments are put in the Values property of the RouteData class• Values is a dictionary whose keys are the route segment names• MVC uses the controller value to find the controller, and the action
value to find the action method• Also accessible in the controller as the RouteData property
• Custom route segments can also be received as parameters of action methods
Using Route Values
RouteData.Values["action"]C#
RouteData.Values("action")VB
public ActionResult List(int id)C#
Function List(id As Integer) _As ActionResult
VB
Mapped from an integer route value named id
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Convention-based routes are registered in a route table• Typically when application starts• VS project templates add a RouteConfig class in App_Start folder
– Called from Application_Start in global.asax
Default route table
Registering Routes
routes.MapRoute(name:="Default",url:="{controller}/{action}/{id}",defaults:=New With{.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
)
VB
routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new{ controller = "Home", action = "Index", id = UrlParameter.Optional }
);
C#
Default controller is Home Default action is Index id parameter is optional
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A route table often has multiple routes• When a request is received, each route is analyzed in turn• In the order the routes were added to the table• First match wins
Put most restrictive routes first• The first route will catch a URL like /List/2• Controller and action are hard-coded in the route
Adding a New Route
routes.MapRoute("List", "List/{id}", new { controller = "ListingItem", action = "ItemList" });
routes.MapRoute("Default", // Default route omitted (see previous slide)
C#
routes.MapRoute("List", "List/{id}",New With {.controller = "ListingItem", .action = "ItemList"})
routes.MapRoute("Default", 'Default route omitted (see previous slide)
VB
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Further customizing the route table is possible• But is much easier to do with attribute routing• New in MVC 5• Can be downloaded as a NuGet package for previous versions
To use attribute routing• Add an initialization line in the RouteConfig.RegisterRoutes method
• Add Route attributes on action methods and/or controller classes
Attribute Routing
routes.MapMvcAttributeRoutes()routes.MapMvcAttributeRoutes(); C# VB
[Route("List/{id}")]public ActionResult ItemList(int id)
<Route("List/{id}")>Function ItemList(id As Integer) As ActionResult
C#
VB
A URL like /List/2will be mapped to the ItemList action method
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Default values can be defined for route segments• To define URL /List to be equivalent to /List/1:
Default values can also apply to action methods• To define Index as the default action method, apply attribute to controller:
A parameter can be made optional with a ? suffix• The following route will be processed for /List/Food or /List
Default Values
Route("List/{id=1}")
Route("{action=Index}")
Route("List/{name?}")
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Route constraints restrict a route to specific data types or values• Apply constraint to route segment
• This route will only apply if the id segment of the URL is an integer
Many types of constraints are defined• alpha, bool, datetime, decimal, double, float, guid, int, length, long, max, maxlength, min, minlength, range, regex
• Can also be chained
• This route will only apply if the id segment of the URL is an integer between 0 and 10
Route Constraints
Route("List/{id:int}")
Route("List/{id:int:min(0):max(10)}"
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In a controller, many action methods can use a common segment• Usually the controller name
• Can be set once with a RoutePrefix attribute on the controller
Factorizing Route Segments
[Route("Home/Index")]public ActionResult Index()
<Route("Home/Index")>Function Index() As ActionResult
C# VB
[RoutePrefix("Home")]public class HomeController : Controller{
[Route("Index")]public ActionResult Index()
C#
<RoutePrefix("Home")>Public Class HomeController
Inherits System.Web.Mvc.Controller
<Route("Index")>Function Index() As ActionResult
VB
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoFactorizing Route Segments Your instructor will demonstrate factorizing route segments
• Open the solution at C:\977\xx\Demo\Chapter 4\AttributeRouting• Note that the default route has been removed from RouteConfig• Open HomeController. Note that Route attributes have been defined. Note
also the use of an empty route template for the default route
Factorizing the Home segment of the routes• Add a RoutePrefix for Home to the controller• Remove the Home segment from the action methods
Overriding the route prefix• Change the empty route on Index to ~/• Add a ~/Show route for the Display action method
Completed demo is at C:\977\xx\Demo\Chapter 4\AttributeRouting - Completed
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 4.2: Customizing Routes
Hands-On Exercise 4.2
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Some resources must not be processed by the route map• *.axd resources are processed by ASP.NET HTTP handlers• Can contain compressed JavaScript bundles
IgnoreRoute stops processing for the mapped path• Visual Studio templates add this line to the RegisterRoutes method
• Any request URL that has an axd extension will be ignored• resource is the name of the resource in the URL• pathInfo contains the remaining parts of the URL (catchall)
The URL is passed to ASP.NET• The axd extension redirects it to the corresponding HTTP handler
Bypassing the Route System
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Outgoing routing builds URLs using the route table• The ActionLink HTML helper uses the route table• Output with the default route:
RouteLink is similar• But can also create a link for other resources, such as files• This link is the same as the previous one:
The Url helper class helps create a URL following the route table
Outgoing Routing
@Html.ActionLink("About", "About", new { id = 15 })
<a href="/Home/About/15">About</a>
@Html.RouteLink("About", new { action = "About", id = 15 })
var url = Url.RouteUrl(new { action = "About", id = 15 });
URL contains /Home/About/15
C#
Dim myUrl = Url.RouteUrl(New With {.action = "About", .id = 15})VB
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ActionLink uses the defined Route attributes to create links• Can be seen in previous demo and exercise
Html.RouteLink and Url.RouteUrl overloads take a route name• Can be used with attribute routing• Must add a name to the Route attribute
• Can be used with
• Or
Outgoing Routing with Attribute Routing
[Route("~/Show", Name="ShowRoute")]
@Html.RouteLink("Display", "ShowRoute")
<a href="@Url.RouteUrl("ShowRoute")">Display</a>
Code at C:\977\xx\Demo\Chapter 4\Outgoing AttributeRouting
<Route("~/Show", Name:="ShowRoute")>
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Controller Class
Action Methods and ActionResult
Filters
Routing
Areas
Chapter Contents
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ASP.NET MVC applications can become big• With hundreds of controllers and thousands of views• Managing and naming views and controllers can become difficult
Areas add another dimension to the project• A new Areas folder where the Model View
Controller structure is replicated• Can have as many areas as needed
To add an area to an ASP.NET MVC project• Right-click the project, select Add | Area,
and name the area• First time, the Areas folder is created• Controllers, Models, and Views folders
are added to each area
The Need for Areas
Admin area
Blog area
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Each area adds entries to the route table• In a class that is added in the area root folder• All AreaRegistration-derived classes are called from global.asax
To use attribute routing with areas:• Remove the AreaRegistration-derived class• Add a RouteArea attribute to the area’s controllers• Define RoutePrefix and default action
Routing and Areas
AreaRegistration.RegisterAllAreas();
[RouteArea("Admin")][RoutePrefix("Users")][Route("{action}")]public class UsersController : Controller <RouteArea("Admin")>
<RoutePrefix("Users")><Route("{action}")>Public Class UsersController
Inherits Controller
VB
C#
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ActionLink can generate links to areas• Add an area property to the RouteValues parameter
Views in an area have their own layout page• Can reuse the main layout view with a _ViewStart.xxhtml in the area
Outgoing Links to Areas
@(Html.ActionLink("Administration", "Index", new { area = "Admin", controller = "Users" }))
C#
@Html.ActionLink("Administration", "Index",New With {.area = "Admin", .controller = "Users"})
VB
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 4.3: Structuring an Application With Areas
Hands-On Exercise 4.3
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we have
Created controllers with the Controller class
Written action methods with parameters
Examined the different types of action results
Written and used filters
Customized route tables
Structured applications with areas
Chapter Summary
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 4-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Which interface must a controller implement?
What is the return type of an action method?
How does MVC find the controller to instantiate from its name?
Name some built-in filters
What are the two main responsibilities of the routing system?
How would you structure an MVC application that has many controllers?
Chapter Review
Forms and User Input
Chapter 5
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Build forms to let users input data
Simplify HTML coding with HTML helpers
Develop custom HTML helpers
Use data annotations to enforce validation and business rules
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML Forms and MVC Simplifying HTML Generation With Helpers
Developing Custom HTML Helpers
Display and Editor Helper Methods
Validating Data
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Can be done with• Standard HTML forms• HTML with JavaScript and Ajax to have a more precise control
In all cases, the developer has full control of the HTML• A single page can have several forms
– ASP.NET Web Forms are limited to a single server-side form
Forms can be designed with standard HTML input elements• Can be simplified and optimized with HTML helpers• Can even have just one line of Razor code
– Everything is then driven from the model
Visual Studio can also scaffold forms from the models• Razor and HTML code is generated by Visual Studio• Can be customized
Getting Input From Users
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
User input is done with HTML form elements• Specific elements—input, textarea, select—are placed inside the form• The browser builds a string with the element names and their values• The string is sent to the server with the request when the form is submitted
With MVC, the form action attribute is the name of an action method• Each input element should have a name attribute• Form is submitted with an input element of type submit
HTML Forms
<form action="/Home/Index">Title: <input type="text" name=“Title" /><br />Notes: <textarea name=“Notes"></textarea><input type="submit" value="OK" />
</form>
Action method called when form is submitted
Name must be supplied
Submit button
HTML elements can also have an id attribute, used on the client side by CSS and JavaScript. name and id usually have the same value but can be different.
CSS = Cascading Style Sheets
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Default values can be set in the model• Or in ViewBag properties• Values are set in the controller• Or better, with a call to the service layer
Supplying Default Values
<form action="/Home/Index">Title: <input type="text" name=“Title" value="@Model.Title" /><br />Notes: <textarea name=“Notes">@Model.Notes</textarea><input type="submit" value="OK" />
</form>
Default values
var model = new ListingItem { Title = "Meeting", Notes = "At 5pm" };return View(model);
C#
Dim model = New ListingItemModel With {.Title = "Meeting", .Notes = "At 5pm"}Return View(model)
VB
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Form data is sent with the request• With this syntax: name1=value1&name2=value2• If the form element has a get method attribute, the data is placed in the URL• With a post method attribute, the data is placed in the HTTP request body
The application on the server can extract the data from the request• The Form dictionary contains the entered data• The data is HTML-encoded to remove special characters such as blanks
Form Data
<form action="/Home/Test" method="post">Title: <input type="text" name="title" />Notes: <textarea name="notes"></textarea>
title=Meeting¬es=With+Stacy%0D%0Aat+5pm
Data is encoded
With the post method, data is put in the request body
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
With MVC, getting the entered data can be simplified• No need to dig into the HTTP or decode HTML data• MVC maps input elements to corresponding action method parameters
– Maps element name to parameter name• Can also map complex objects
Processing Form Data in an Action Method
<form action="/Home/Index" method="post">Title: <input type="text" name="title" />Notes: <textarea name="notes"></textarea>
[HttpPost]public ActionResult Index(string title, string notes){
}
C#
<HttpPost>Public Function Index(title As String, notes As String) As ActionResult
End Function
VB
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Two action methods are usually associated with one form• First action method processes a GET request to display the form• Second method processes a POST request after the form has been submitted• Use same method name for both
– Compiler distinguishes methods by signature– Routing distinguishes methods with HttpPost attribute on second method
One Form, Two Action Methods
public ActionResult Index(){
var model = ...;return View(model);
}
[HttpPost]public ActionResult Index(ListingItemModel model){
return View("Confirm", model);} C#
Public Function Index() As ActionResultDim model = ...Return View(model)
End Function
<HttpPost>Public Function Index(model As ListingItemModel) _
As ActionResultReturn View("Confirm", model)
End Function
VB
Navigate to other view, once processing is done
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
One Form, Two Action Methods—Illustrated
GET initial request
Form
User clicks a link or button to request the form
Get action method
ControllerBrowser
Post action method
POST request
Next page
FormUser submits the form
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoExperimenting With an HTML Form Your instructor will demonstrate an HTML form
• Solution in C:\977\xx\Demo\Chapter 5\HTMLForm• Home controller has two Index action methods
– Index view has an HTML form– Confirm view displays entered data
• Run the application and click OK– Form data is displayed in Visual Studio Output window
• Change the method value in the form to get; run and click OK– Index view is displayed again– Form data is in the URL
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 5a: Editing Items in an HTML Form1. Open the Do Now 5a starting point in C:\977\xx\Do Nows\Do Now 5A-
Starting Point and build the solution• This is the solution to the last exercise with additional item-editing features
2. Open the ListingItemController• It has two ItemEdit action methods
3. What is the type of the parameter of the second ItemEdit method?______________________________________________________________
3. Open the ListingItem\ItemEdit view• It implements a form including several fields from the model
• What is the model type for the view? ______________________________
4. Run the application and navigate to the ItemEdit form• A form is displayed, but its data is not saved yet
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML Forms and MVC
Simplifying HTML Generation With Helpers
Developing Custom HTML Helpers
Display and Editor Helper Methods
Validating Data
Chapter Contents
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML helpers are methods that generate HTML• Like the ActionLink helper• Help generate clean HTML• Keep element name attribute and model property in sync
Html.BeginForm generates the form element• Has several overloads• With a using block, it will also generate the closing form tag• Removes the need for the clumsy EndForm method
HTML Helpers
@using (Html.BeginForm()){
Title: <input type="text" ...}
C# @Using Html.BeginForm
@:Title: <input type="text" ...End Using
VB
<form action="/Home/Index" method="post">
Generates
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Parameter-less BeginForm generates a default form • Method is POST• Action is the current action method• Overloads specify the controller, the action method, or add HTML attributes
BeginForm Overloads
Html.BeginForm("Edit", "Listing", FormMethod.Get,new { id = "myForm", @class = "formClass" })
C#
Html.BeginForm("Edit", "Listing", FormMethod.Get,New With {.id = "myForm", .class = "formClass"})
VB
<form action="/Listing/Edit" class="formClass" id="myForm" method="get">
Note the use of @class, as class is a reserved word in C#
Generates
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Several HTML helpers generate input elements• Each has overloads to add attributes or specify a default value• For example
can be replaced by
First parameter is the value of id and name properties• Can be overridden with an anonymous object• Second parameter is usually the default value
Input Elements Helpers
<input type="text" id="title" name="title" value="@Model.Title" />
@Html.TextBox("title", Model.Title)
@Html.TextBox("title", Model.Title, new { id = "idTitle" })C#
@Html.TextBox("title", Model.Title, New With { .id = "idTitle" })VB
<input id="idTitle" name="title" type="text" value="Meeting" />
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Main input HTML helpers• name and id attributes not shown for simplicity
Input HTML Helpers
Helper method HTML elementTextBox <input type="text" />
TextArea <textarea></textarea>
Password <input type="password" />
CheckBox <input type="checkbox" />
RadioButton <input type="radio" />
Hidden <input type="hidden" />
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
All input HTML helpers have strongly typed counterparts• Take a lambda expression for the field name• IntelliSense displays the field name and avoids typing mistakes• Same name as nontyped methods, with a For suffix• Use strongly typed helpers whenever possible
Strongly Typed HTML Helpers
@Html.TextBoxFor(m => m.Title)C#
@Html.TextBoxFor(Function(m) m.Title)VB
<input id="Title" name="Title" type="text" value="Meeting" />
Value of the Titleproperty in the model
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Label and LabelFor display a label HTML element• Displays the associated property name of the model by default • Can be changed with a Display attribute in the model
– Defined in System.ComponentModel.DataAnnotations– Can also be used with other helpers
HTML Helpers for Labels
@Html.LabelFor(m => m.Title)C#
@Html.LabelFor(Function(m) m.Title)VB
[Display(Name="Please enter title:")]public string Title { get; set; }
C#
<label for="Title">Please enter title:</label>
for associates the label with the textbox
<Display(Name:="Please enter title:")>Property Title As String
VB
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML lists use a select element• Has a list of option elements• Each option has a value attribute and displayed text• Displays list box if size attribute is greater than 1, a drop-down list otherwise
A Razor view can manually build a list with a foreach loop
HTML List Boxes and Drop-Down Lists
<select>@foreach (var item in Model){
<option value="@item.Id">@item.Title (@item.Notes)</option>}
</select>
C#
<select>@For Each item In Model
@<option value="@item.Id">@item.Title (@item.Notes)</option>Next
</select>
VB
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Two HTML helpers produce HTML lists• DropDownList and ListBox or their strongly typed versions• They take a SelectList object as parameter• SelectList has several overloads and encapsulates the list to be displayed
Two options to build the SelectList• In the view, as in the example on this slide• In the controller or service layer, in a property of the model or the ViewBag
List Helpers
@Html.DropDownList("list", new SelectList(Model, "Id", "Title", 2))C#
@Html.DropDownList("list", new SelectList(Model, "Id", "Title", 2))VB
List nameIenumerableList to display
Valueproperty
Textproperty
Default value
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DropDownListFor With a SelectList in a Model (C#)
public class ListingModel{
public SelectList List { get; set; }public int SelectedId { get; set; }
}
C#: Model
@using (Html.BeginForm()){
@Html.DropDownListFor(m => m.SelectedId, Model.List)<input type="submit" value="OK" />
}
C#: View
public ActionResult ListWithModel(){
var model = new ListingModel { List = new SelectList(_list, "Id", "Title") ,SelectedId = 2 };
return View(model);}
[HttpPost]public ActionResult ListWithModel(ListingModel model){ ... }
C#: Controller
List
Selected item
model.SelectedIdhas the selected value
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DropDownListFor With a SelectList in a Model (VB)
Public Class ListingModelPublic Property List As SelectListPublic Property SelectedId As Integer
End Class
VB: Model
@Using Html.BeginForm()@Html.DropDownListFor(Function(m) m.SelectedId, Model.List)@<input type="submit" value="OK" />
End Using
VB: View
Public Function ListWithModel() As ActionResultDim model = New ListingModel() With _
{ .List = New SelectList(_list, "Id", "Title"), .SelectedId = 2 }Return View(model)
End Function
<HttpPost> _Public Function ListWithModel(model As ListingModel) As ActionResult
...End Function
VB: Controller
List
Selected item
model.SelectedIdhas the selected value
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoUsing List HTML Helpers Your instructor will demo list HTML Helpers
• Solution in C:\977\xx\Demo\Chapter 5\ListHelpers• Click HTML DropDown to display a manually generated select element• Click DropDownList to display a drop-down list generated with a DropDownList helper
• Click DropDownListFor with model to display a drop-down list using a DropDownListFor helper
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Uploading a file can be done with an input type="file" element• Must be in a form that uses the POST method and has an enctype attribute
Action method receives the file as a parameter• Type is HttpPostedFileBase• Also available through the Request.Files property
Uploading Files
@(using (Html.BeginForm("AddPhoto", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })))
{<input type="file" name="file" /><input type="submit" value="Upload" />
}
C#
[HttpPost]public ActionResult AddPhoto(HttpPostedFileBase file){}
C#
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HttpPostedFileBase properties and methods
Server object in controller has a MapPath method• Returns the physical path on the server for a logical path
Processing Uploaded Files
Property or method DescriptionContentLength Size of file in bytesContentType MIME type of fileFileName Full name of file on the clientInputStream Stream that points to the file contentSaveAs Method to save the file on the server
Server.MapPath("~/Photos");
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoUploading Photos Your instructor will demo uploading photos to a website
• Solution in C:\977\xx\Demos\Chapter 5\Photos• Run the application; click Browse to select a photo
– There are some photos in C:\977\Database\Photos• Click Upload to upload the selected photo• Click Show All Files in Solution Explorer
– The uploaded photos are in the Photos folder of the project• Examine the HomeController class and the Index view
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 5.1: Replacing HTML Elements With HTML Helpers
Hands-On Exercise 5.1
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML Forms and MVC
Simplifying HTML Generation With Helpers
Developing CustomHTML Helpers
Display and Editor Helper Methods
Validating Data
Chapter Contents
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Most MVC HTML helpers are extension methods• Methods that extend the HtmlHelper class• Custom HTML helpers can be written
An extension method seems to be part of a class• Can be added to existing classes• Especially useful when the source code of the class is not available
– For example, the .NET Framework classes
Must be defined in a static class (C#) or Module (VB)• First parameter of the method is the object to which the method applies• In the client, add a using / Imports for the namespace where it is defined
A custom HTML helper should return a string• HTML that is inserted in the view• Return an HtmlString so that Razor doesn’t encode the string• Can use the TagBuilder class to help build the HTML
Extension Methods
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Method that builds a link made of text and image• The standard ActionLink method generates an <a> element with text• The ImageActionLink custom helper will generate an <a> element with
image and text
An extension method is used as if it were part of the class it extends• The Html property of views is of type HtmlHelper
An HTML Helper Extension Method
@Html.ImageActionLink(...)HtmlHelper
instance
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
An HTML Helper Extension Method
Public Module MyExtensions<Extension>Public Function ImageActionLink(html As HtmlHelper, ...) As HtmlString
End FunctionEnd Module
Method must be in module
Extension attribute for extension method
public static class MyExtensions{
public static HtmlString ImageActionLink(this HtmlHelper html, ...{
}}
C#
Class and method must be static
First parameter decorated with this
VB
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Simple class to help building HTML elements• Constructor takes the name of the element
• Methods and properties to customize the element
The TagBuilder Class
var link = new TagBuilder("a");C#
Dim link = New TagBuilder("a")VB
Method/Property DescriptionAddCssClass Add values to the class attributeMergeAttribute Add an attribute to the elementSetInnerText Set text between the opening and closing tags (encoded)Attributes Attributes dictionary
InnerHtml Set HTML between the opening and closing tags (not encoded)
ToString Return HTML string for element
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Builds URLs from route values• Can be accessed through the Url property in views• Constructor takes a request context
• Methods return URLs
The UrlHelper Class
Method Description
Action Several overloads to generate a URL from action, controller, route values
RouteUrl Generate a URL from a route nameContent Convert a virtual path to an absolute path
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);C#
Dim urlHelper = New UrlHelper(html.ViewContext.RequestContext)VB
Extending the HtmlHelper class gives access to its members
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Building an Anchor Link
var link = new TagBuilder("a");link.Attributes.Add("href",
urlHelper.Action(actionName, controllerName, routeValues));link.SetInnerText(linkText);// Use with: link.ToString()
C# Parameters passed to the extension method
<a href="/ListingItem/List/1">Food</a>
@Html.MyActionLink(listing.Title, "List", "ListingItem", new { id = listing.Id })
Dim link = New TagBuilder("a")link.Attributes.Add("href",
urlHelper.Action(actionName, controllerName, routeValues))link.SetInnerText(linkText)' Use with: link.ToString()
VB
View: C#
@Html.MyActionLink(listing.Title,"List", "ListingItem", New With {.id = listing.Id})
View: VB
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 5b: Using a Custom HTML Helper
1. Open the Do Now 5b starting point inC:\977\xx\Do Nows\Do Now 5b-Starting Point
2. Run the application and click on the My Lists link; notice that the links work as expected
3. Open the MyExtensions class in the Extensions folder in the Webproject
4. Try to understand the code; ask your instructor if you have questions
5. Go to List view in the Views\Listing folder
6. Delete the lines of code that generate the link and the image
7. Uncomment the last two lines that call the ImageActionLink method
8. Back in the running application, navigate to the My Lists page. It should work as before
9. Look at the page in source view to see the generated HTML links
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Extending the HtmlHelper class gives access to its properties and methods• Such as ViewData, ViewBag, or ViewContext• And to the ViewContext properties such as HttpContext or RequestContext
MVC also has some useful helper classes• ExpressionHelper gets the text of an expression• ModelMetadata gives access to the model metadata such as DisplayName• Used in bonus section of next exercise
The HtmlString class encapsulates a string• Tells the Razor engine not to encode the string• Was introduced in .NET 4.0• MvcHtmlString has a similar purpose—can be used for pre-.NET 4.0
applications
Helper Classes
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 5.2: Developing a LabelTextBox HTML Helper
Hands-On Exercise 5.2
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML Forms and MVC
Simplifying HTML Generation With Helpers
Developing Custom HTML Helpers
Display and Editor Helper Methods
Validating Data
Chapter Contents
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
MVC can generate the view display and input elements from the model• Selects the HTML elements depending on the property data type• Can be customized with attributes• Used this way, a model is often called a view model
Uses Editor and Display helper methods• Or their strongly typed counterparts, EditorFor and DisplayFor• The generated HTML element depends on the type of property• EditorForModel and DisplayForModel generate elements for the whole
model
Editor and EditorFor generate input HTML elements• Type is text by default• Can be checkbox for Boolean properties• Can also be number or datetime on HTML5-compliant browsers
Display and DisplayFor generate plain text• Or disabled checkboxes for Boolean properties• Everything can be customized
Model-Driven User Interface
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
EditorForModel renders input fields for each model property• DisplayForModel displays each model property• Properties can be hidden or formatted with attributes
Controlling each property display is done with attributes in the model• Defined in System.ComponentModel.DataAnnotations and System.Web.Mvc namespaces
Editing and Displaying the Whole Model
Attribute Description
ScaffoldColumnIf constructor is passed false, no HTML is rendered for property
HiddenInputGenerates an input type="hidden" element for Editor methods; no HTML rendered with Displaymethods if DisplayValue is false
DisplayFormatControls the formatting of the output;NullDisplayText is the text displayed if value is null; DataFormatString is a formatting string
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Using Editor and Display Attributes
[HiddenInput(DisplayValue = false)]public int Id { get; set; }
[DisplayFormat(NullDisplayText = "-", DataFormatString="{0:D}")][Display(Name = "Due Date")]public DateTime? DueDate { get; set; }
[ScaffoldColumn(false)]public int? LookAndFeelId { get; set; }
C#
@Html.DisplayForModel()
<HiddenInput(DisplayValue:=False)>Property Id As Integer
<DisplayFormat(NullDisplayText:="-", DataFormatString:="{0:D}")><Display(Name:="Due Date")>Property DueDate As DateTime?
<ScaffoldColumn(False)>Property LookAndFeelId As Integer?
VB
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
EditorFor replaces more specific HTML input methods• The generated HTML is driven by data type• Can be customized with attributes
Editor and EditorFor
@Html.TextBoxFor(m => m.Title)@Html.CheckBoxFor(m => m.Done)@Html.TextBoxFor(m => m.Notes)
C#
@Html.EditorFor(m => m.Title)@Html.EditorFor(m => m.Done)@Html.EditorFor(m => m.Notes)
C#
@Html.TextBoxFor(Function(m) m.Title)@Html.CheckBoxFor(function(m) m.Done)@Html.TextBoxFor(function(m) m.Notes)
@Html.EditorFor(Function(m) m.Title)@Html.EditorFor(function(m) m.Done)@Html.EditorFor(function(m) m.Notes)
VB
VB
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Editor and EditorFor generate HTML according to property data type• Most data types generate input of type text• Can be customized with a DataType attribute
– Or with a UIHint attribute
The DataType attribute changes the template used to generate HTML• MVC has built-in display and edit templates for each data type
– Custom templates can also be created• DataType also has some derived classes
– The two following attributes are equivalent
– and
Customizing the Generated HTML
[EmailAddress]C#
[DataType(DataType.EmailAddress)]C#
<DataType(DataType.EmailAddress)>
<EmailAddress>
VB
VB
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Main DataType enumeration values
Other values will generate validation code• CreditCard, PhoneNumber, PostalCode…• Validate the format, not the value
DataType Attribute
DataType value DescriptionMultilineText Generates a textarea HTML elementPassword Generates an input of type passwordDate, Time Display the date or time part of a DateTime propertyEmailAddress Generates a mailto: anchor elementUrl Generates an anchor element
Validation is covered in next section
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Custom display and editor templates can be defined• Partial views located in DisplayTemplates or EditorTemplates folder
under the Shared folder• Model type is the property type• Implicitly associated with a property through the type name
– Boolean.xxhtml will process all bool/Boolean properties– Replaces the built-in Boolean template
• Or explicitly with a UIHint or DataType attribute
Your instructor might choose to demo a display template• Solution in C:\977\xx\Demo\Chapter 5\DisplayTemplate• Look for the Boolean template in Views\Shared\DisplayTemplates• The ListingItemModel class has a Boolean property• The Display view displays the Done property using the template
Custom Display and Editor Templates
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 5.3: Using Edit and Display Templates
Hands-On Exercise 5.3
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
HTML Forms and MVC
Simplifying HTML Generation With Helpers
Developing Custom HTML Helpers
Display and Editor Helper Methods
Validating Data
Chapter Contents
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Data input must be verified before it reaches the database• Should be done on the client and the server• On the client, uses JavaScript code• On the server, validation is done in the controller
– The business layer can do additional verifications, applying business rules
ASP.NET MVC does the server-side validation during model binding• Also adds attributes to elements to do validation on the client
Client and Server Validation
50© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Comparing posted data and data in the model• Data that cannot be converted into the destination type is ignored• Posted data—in the request body:
• Model – in action method parameter:
Validation During Model Binding
ListingId=1&Title=Cookies&Done=false&Notes=&Quantity=Ten&Priority=Normal&DueDate=todayTen today
51© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
ModelState is a dictionary• Keys are field names• Values have an Errors collection• IsValid property is false if at least one Errors collection is not empty
ModelState is filled during model binding in the action method• An error is added for each binding failure
– For example, trying to put a text string in a numeric property– Or if the input value doesn’t match some data annotation attribute
ModelState
52© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Binding validation is done by MVC before calling the action method• The View method will add an input-validation-error class to any field
that has an error
Validating the Model in an Action Method
[HttpPost]public ActionResult ItemEdit(ListingItemModel model){
if (!ModelState.IsValid)return View(model);
_listingItemService.Update(model);return RedirectToAction(“ItemList", new { id = model.ListingId });
}
If errors found, return view
No error found
C#
<HttpPost>Public Function ItemEdit(model As ListingItemModel) As ActionResult
If Not ModelState.IsValid ThenReturn View(model)
End If_listingItemService.Update(model)Return RedirectToAction(“ItemList", New With {.id = model.ListingId})
End Function
VB
If errors found, return view
No error found
53© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Custom model validation can be done in the action method• IsValidField tests if a field is valid• Application can add items in the dictionary with AddModelError method
Adding Custom Validation
if (ModelState.IsValidField("Quantity") && model.Quantity.HasValue && model.Quantity < 0)
ModelState.AddModelError("Quantity", "Quantity must not be negative");
If Quantity is valid, checking if not negative
C#
If ModelState.IsValidField("Quantity") AndAlso model.Quantity.HasValue AndAlsomodel.Quantity < 0 Then
ModelState.AddModelError("Quantity", "Quantity must not be negative")End If
VB
54© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The ValidationMessageFor HTML helper displays an error message• Using field-validation-error CSS class• Use one for each field that can have errors• ValidationSummary displays a list of all errors found in the page
Displaying Error Messages
@Html.ValidationSummary("Errors found:")
@Html.LabelFor(m => m.Quantity)@Html.EditorFor(m => m.Quantity)@Html.ValidationMessageFor(m => m.Quantity)(remaining lines omitted)
C#
@Html.ValidationSummary("Errors found:")
@Html.LabelFor(Function(m) m.Title)@Html.EditorFor(Function(m) m.Title)@Html.ValidationMessageFor(Function(m) m.Title)(remaining lines omitted)
VB
Text passed to AddModelError
Default text supplied by MVC
input-validation-errorclass defined in Site.css
55© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Many validation rules are encapsulated in attributes• Defined in System.ComponentModel.DataAnnotations namespace• All attributes have an ErrorMessage property to specify the error message
Controlling Validation With Attributes
Attribute DescriptionRequired Field must not be blankStringLength Specify maximum and minimum lengthCompare Value should be equal to another propertyRange Value between two numbers or other typesCreditCard Valid credit card number formatEmailAddress Valid e-mail address formatPhone Valid phone number formatRegularExpression Validate field with regular expression
56© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In a class that derives from ValidationAttribute abstract class• Implement the IsValid method• Receives the property value as an object• Return true if validation succeeds, false if it fails
Defining a Custom Validation Attribute
public class FutureDateValidationAttribute : ValidationAttribute{
public override bool IsValid(object value){
var date = value as DateTime?;return date == null || date > DateTime.Today;
}}
C#
Public Class FutureDateValidationAttributeInherits ValidationAttribute
Public Overrides Function IsValid(value As Object) As BooleanDim dt = CType(value, DateTime?)Return dt Is Nothing OrElse dt > DateTime.Today
End FunctionEnd Class
VB
57© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
MVC validation is done on the server by default• Form must be posted for validation to occur• Not very responsive
ASP.NET MVC integrates well with jQuery validation• Adds validation attributes to elements starting with data-val
– Such as data-val-required or data-val-length
To enable validation on the client• Add two lines in Web.Config in the appSettings section
– Already set in Visual Studio MVC templates
• Add the jqueryval bundle to the page or layout– Already defined in BundleConfig class
Validating on the Client
<add key="ClientValidationEnabled" value="true" /><add key="UnobtrusiveJavaScriptEnabled" value="true" />
@Scripts.Render("~/bundles/jqueryval")
More on bundlesin next chapter
58© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 5.4: Adding Validation to the Case Study
Hands-On Exercise 5.4
59© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Visual Studio can scaffold views from a model• Builds the view from the model properties• Select template in the Add View dialog• Can add views for Create, Delete, Details, Edit, List
Visual Studio can also scaffold a controller from a model• Adds methods for the CRUD operations• Select type of scaffolding in Add Controller dialog
Scaffolding With Visual Studio
Template to use
Model class
60© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 5c: Experimenting With Scaffolding
1. Open the Do Now 5c starting point inC:\977\xx\Do Nows\Do Now 5c-Starting Point
2. Open the ListingItemController in the ListPlus.Web project• A new action method has been added at the end: ScaffoldDisplay• It is a copy of the ItemDisplay method with a different name
3. Right-click in the ScaffoldDisplay method and select Add View
4. Select Details for Template and ListingItemModel for Model class• With Visual Basic, add the namespace to the ModelType line in the view
5. In the ItemList view, modify the ActionLink, replacing ItemDisplaywith ScaffoldDisplay
6. Run the application• The scaffolded view should be displayed when you select an item
7. If you have more time, adjust the generated links in the scaffolded view so that they work correctly• Change also the action name in the ItemEdit method
61© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we have
Built forms to let users input data
Simplified HTML coding with HTML helpers
Developed custom HTML helpers
Used data annotations to enforce validation and business rules
Chapter Summary
62© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 5-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Write the Razor code that generates a form in a view
Name some HTML helpers for input fields
Which class is used to generate a drop-down list?
Which language feature is used to create a custom HTML helper?
How can you know if model binding succeeded?
Write the code that limits input of a Name property to 20 characters
Chapter Review
Client-Side Features
Chapter 6
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Build highly interactive applications with the help of jQuery
Develop client-side UI elements with jQueryUI
Optimize page loading time with bundling and minification
Make client and server communicate smoothly with Ajax
Make an application mobile-friendly
Prepare applications for international markets
Use grids and charts to display data on pages
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction to jQuery Ajax
Adapting to Mobile Devices
International Applications
WebGrid and Chart
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Server
ASP.NET MVC is a server-side technology• HTML, CSS, images are sent from the server• The browser displays the pages• When the user clicks a link or submits a form, a request is sent to the server
To make an application more effective, client-side development is required• Attractive dynamic UIs: menus, animations, date-pickers …• Request data from the server without refreshing the whole page• Done in the browser, with JavaScript code
Server-Side and Client-Side Technologies
Model
View
Client
Browser Controller
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
JavaScript is a C-type dynamic language• Implemented in all modern browsers• JavaScript code is included in HTML pages• Runs on the browser• Has access to the Document Object Model (DOM)
– Hierarchical representation of the HTML document
jQuery hides most browser specificities• Lightweight, open-source JavaScript library included in Visual Studio• Download, update, and get documentation at jquery.com
– Can also be updated via NuGet
Main jQuery functionality• Manipulate the HTML DOM: elements, attributes, classes, etc.• Process JSON—compact data description syntax, light alternative to XML• Separating behavior from content with unobtrusive JavaScript• Thousands of plug-ins are available to add functionality
JavaScript and jQuery
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
jQuery is published as a .js file• Must be included in a page to use it• Typically done in a layout page• Automatically added through bundles in most MVC project templates
jQuery function is the core of the jQuery API• jQuery passes a selector to an expression• Returns the jQuery object—a set of matched elements• Written as jQuery() or $()
jQuery code should not run before all HTML is loaded• jQuery.ready() event runs when the DOM has loaded• Written as $(function () { … });
Introducing jQuery
Your jQuery code goes here
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A jQuery selector references one or more elements in the DOM• Based on CSS selectors• Syntax is $('selector')
Many types of selectors are defined, here are a few
jQuery Selectors
Selector Description$('button') All button elements on the page$('#btn') Element whose id attribute is btn$('.cancel') All elements who have a class name of cancel
$('li.opt input')All input elements that are inside an li element with a class name of opt
1610®
To learn more on jQuery: Course 1610, jQuery Introduction
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Displaying an alert message when the user clicks a button• With jQuery, the code is in a different part of the HTML page• Or better, in a separate .js file referenced by the page• jQuery is said to be unobtrusive
Using jQuery
<input type="button" value="Click me" id="button" />
@section scripts {<script>
$(function () {$('#button').click(function () {
alert('Thanks!');});
});</script>
}
script section defined in layout
Will be called when DOM is loaded
Adds clickevent handler
Parameter is a function, called when event is raised
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemojQuery in Action Your instructor will demonstrate a page with jQuery code
• Start application• Select jQuery or Animation• Click a color
C:\977\xx\Demo\Chapter 6\jQuery
<ul id="colors"><li><a data-color="red" href="#">Red</a></li><li><a data-color="green" href="#">Green</a></li><li><a data-color="blue" href="#">Blue</a></li>
</ul>
<div id="divDemo" />$(function () {
$('#colors a').click(function () {var color = $(this).data('color');$('#divDemo').removeClass().addClass(color);
});}); Note the fluent API: each
method returns the object it is called on
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Web pages often need several JavaScript and CSS files• Each is included with a <script> or <link> tag• An HTTP request is made for each• Slows down page loading, especially on mobile devices with a slow network
Bundling and minification are new to .NET 4.5• Had to use add-ons such as Combres with previous versions• Bundling combines several .js or .css files in one file• Minification removes spaces, tabs, new lines, and comments
– Also shortens variable names
Only takes place in production environment• If the debug attribute of compilation element in Web.config is false
Bundling and Minification
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Bundling is defined in the System.Web.Optimization namespace• The BundleTable class has a Bundles static collection• Contains a collection of ScriptBundle and StyleBundle objects• BundleConfig class in the App_Start folder registers the bundles• Called from Application_Start, in Global.asax
Bundles are referenced from pages• Typically in the layout page• Identified by the bundle name
Bundling Configuration
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
C#
Bundle name
Files to include
@Scripts.Render("~/bundles/jquery")
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoDemo: Observing the Effect of Bundling1. Open the solution in
C:\977\xx\Demo\Chapter 6\Bundling
• It is the solution from the last exercise modified slightly
2. Open the _ViewStart view in the Views folder• It defines _LayoutWithoutBundling as the default view
3. Open _LayoutWithoutBundling in the Views\Shared folder• It does not use bundling, but classic link and script elements
4. Run with Internet Explorer using <Ctrl><F5> and press <F12> to display the developer tools
5. Click the Network tab, then check the Always refresh from server button
6. Click the green arrow button to enable network traffic capturing
7. In your application, click the Home menu item
What is the size of the jQuery script file?
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoDemo: Observing the Effect of Bundling8. Close Internet Explorer and change Layout definition in _ViewStart to
9. Open _LayoutWithBundling and look for differences with the _LayoutWithoutBundling view
10. In Web.config, change debug to false in the compilation element• Use the Web.config file located at the application root
11. Run with <Ctrl><F5> and press <F12> to display the developer tools
12. Click the Network tab, then check the Always refresh from server button
13. Click the green arrow button to enable network traffic capturing
14. In your application, click the Home menu item
8. What is the size of the jQuery bundle?
15. Click the Debugger button and select jQuery in Open document menu
Layout = "~/Views/Shared/_LayoutWithBundling.cshtml"
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Many jQuery plug-ins exist• plugins.jquery.com has a partial list• jQuery UI is a very popular one, included with Visual Studio• Bootstrap also has many features and plug-ins
– Works better with recent CSS3-compliant browsers
jQuery UI has many features to enhance the user interface• Drag or resize items on a page• Elaborate animations• Several widgets such as Dialog, Menu, Datepicker, Tabs …
Your instructor might choose to demo jQuery UI• If an Internet connection is available in the classroom• At jqueryui.com/demos
jQuery UI
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 6a: Adding a jQuery UI Datepicker
1. Open the Do Now 6a starting point in C:\977\xx\Do Nows\Do Now 6a-Starting Point
• This is the previous completed exercise to which jQuery UI has been added as a NuGet package
• For the next steps, to uncomment lines, simply select the commented lines, and click the Uncomment button in the toolbar, or press <Ctrl><K>followed by <Ctrl><U>
2. Open the BundleConfig class in App_Start folder. Uncomment the two blocks of lines that define bundles for jQuery UI
3. In the _Layout.xxhtml view, remove the comments from the two lines that are commented, near the top and the bottom of the file
4. Uncomment the scripts section at the bottom of ItemEdit.xxhtml in the ListingItem folder
5. Run your application, go to the edit page, and click the DueDate field• A datepicker lets you select the date
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction to jQuery
Ajax Adapting to Mobile Devices
International Applications
WebGrid and Chart
Chapter Contents
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Combines JavaScript, the DOM, CSS, and the XMLHttpRequest• Allows a partial page refresh
– Normal GET or POST HTTP requests cause a full page refresh• Request goes to an action method• Can return HTML, XML, JSON, text• Response is processed by JavaScript or jQuery code• Browser does not refresh the whole page
Ajax
Client Server
Action methodAction method
jQuery code
2
134
GET or POST
Ajax request
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Ajax requests are normal HTTP requests• Usually GET or POST• Processed by an action method in an MVC application• Asynchronous: The caller is not blocked while the request is being executed
Action method can return any type of data, including• HTML: Use return PartialView to return a partial view• JSON: Use return Json to return JSON data
– Data structure that represent objects, including arrays and collections
jQuery code processes the returned data• Must supply a callback method, called when the response is received• Can update the DOM to change the page layout
Ajax and Action Methods
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
JSON is the native object representation in JavaScript• Object properties are dynamic, they are created on the fly• Data type is implicit
JSON representation of a LookAndFeelModel object• Can use single or double quotes
Very similar to JavaScript object literals• Declare arrays with square brackets
JSON
{"Id": 5,"Name": "Pink","FontName": "Times New Roman","FontSize": 12,"ForeColor": "Pink","BackColor": "LightGreen"
}
JSON
var person = { Name: "Fred", Scores: [ 10, 12, 8 ] };jQuery
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Action methods can return JSON data• With the JsonResult class that derives from ActionResult• Or the Json helper method
jQuery code accesses the properties using their .NET names
Can also use the Json.NET library• Free package that can be downloaded with NuGet• Can convert .NET objects to JSON—Serialization• Or from JSON to .NET—Deserialization• Can also build and manipulate JSON objects from .NET code
MVC and JSON
var item = _lookAndFeelService.Read(id);return Json(item, JsonRequestBehavior.AllowGet);
C#
Pass any object Necessary if action method is GET
Dim item = _lookAndFeelService.Read(id)Return Json(item, JsonRequestBehavior.AllowGet)
VB
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
jQuery has several methods to make Ajax calls to the server• $.ajax method makes an Ajax request to the server• Takes an object literal as a parameter—many options available• Several shortcuts are easier to use
• Using the $.get shortcut
jQuery Ajax Methods
Ajax Description$.get Load data from the server using a GET HTTP request$.post Load data from the server using a POST HTTP request$.getJSON Load JSON from the server using a GET HTTP request
$.get('/ListingItem/EditLookAndFeel', { id: $('#LookAndFeelId').val() }, function (data) {
});
Action method to call
Optional parameters
Function called when response is received
jQuery
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Define a partial view and an action method that returns it• Partial view named EditLookAndFeel
• Action method
Displaying a Pop-Up Modal Dialog With Ajax and jQueryUI
Please select the Look and Feel: @Html.DropDownList("LookAndFeelList")
public ActionResult EditLookAndFeel(int id){
var list = _lookAndFeelService.List();ViewBag.LookAndFeelList = new SelectList(list, "Id", "Name", id);return PartialView();
}
C#
Public Function EditLookAndFeel(id As Integer) As ActionResultDim list = _lookAndFeelService.List()ViewBag.LookAndFeelList = New SelectList(list, "Id", "Name", id)Return PartialView()
End Function
VB
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Call the action method and process the returned data from jQuery code
Displaying a Pop-Up Modal Dialog With Ajax and jQueryUI
$.get('/ListingItem/EditLookAndFeel', { id: $('#LookAndFeelId').val() }, function (data) {$('#divLookAndFeel').html(data).dialog({
modal: true,width: 500,buttons: { /* code omitted */ }}
});});
jQuery
data contains the HTML from partial view
Place the data inside the div
dialog is defined by jQueryUI
Options defined with an object
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 6.1: Using jQuery and Ajax to Display a Dialog Box
Hands-On Exercise 6.1
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction to jQuery
Ajax
Adapting to Mobile Devices International Applications
WebGrid and Chart
Chapter Contents
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Two types of mobile applications • Client applications developed specifically for the mobile OS
– iOS, Android, Windows Phone …– Not the subject of this course
• Web applications accessed through a mobile browser
A mobile browser can access most websites• If the site is not adapted for mobile devices,
the page might be difficult to read• The main challenges for the developer are
screen size and touch interaction
Mobile Applications
Learning Tree has a site adapted to mobile devices.The desktop version has been requested here for demonstration purposes!
iOS = iPhone OSOS = operating system
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Two main strategies to adapt an application for mobile devices• Defining CSS rules for smaller screen sizes• Creating specific views for mobile devices
Specific CSS rules are defined in an @media CSS section• Will be applied to any small screen, even on a non-mobile device
Bootstrap is included with Visual Studio and defines many CSS rules• Used in the ListPlus application
Adapting Applications for Mobile Devices
@media only screen and (max-width: 850px) {
}
Applies only to screens less that 850 px wide
Any rule defined here overrides previous rules
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Mobile devices define two viewports• The layout viewport, virtual viewport to which the page width is adjusted• The display viewport, whose width is that of the device
The layout viewport width is defined by the browser• Defaults to between 800 and 980 pixels depending on browser
When a page is rendered• Its width is adjusted to the layout viewport width• The page is zoomed so that the
layout viewport fits the display viewport• Consequence: The content of page looks too small
The layout viewport can be defined in a page• Typically in _Layout.xxhtml• To adjust its width to the device width
The Mobile Viewports
Layout viewport width
Display viewport width
<meta name="viewport" content="width=device-width" />
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Testing mobile application can be done with different tools• On a mobile device if it can access the website• With an emulator, such as Opera Mobile Emulator
– Or Windows Phone SDK• By tweaking the user agent string
Each HTTP request has a user agent string in its header• Set by the browser, it identifies the source of the request• Most browsers can change the user agent string to simulate another browser
– In the developer tools settings for IE and Chrome– Entering about:config in the address bar for Firefox or with the User
Agent Switcher extension
Testing Mobile Applications
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Mobile-specific views can be defined• Usually a clone of an existing view, with some modifications• Include Mobile in the name: List.Mobile.cshtml• Can apply to views, layout views, partial views• If request comes from a mobile, the mobile version will be used
ASP.NET uses XML definition files to determine the origin of a request• Compares the user agent string against definition• C:\Windows\Microsoft.NET\Framework\v[n]\Config\Browsers
A view can also test if a request comes from a mobile device
Specific views can be defined for a specific device• Adding an entry to the Modes table of the DisplayModeProvider class• Typically done at application startup in Global.asax
Mobile Views
if (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice){
// Request originates from mobile device}
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In the Application_Start method of Global.asax• List.iPhone.xxhtml will be used if condition is true
Adding a New Display Mode Condition
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone"){
ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
C#
DisplayModeProvider.Instance.Modes.Insert(0, New DefaultDisplayMode("iPhone") With
{.ContextCondition =
(Function(context) context.GetOverriddenUserAgent().IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
})
VB
Part of file nameCondition
Insert in first position
Condition
Insert in first position
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 6.2: Adapting ListPlus to Mobile Devices
Hands-On Exercise 6.2
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
jQuery Mobile is a JavaScript library that builds on top of jQuery• Touch-optimized web framework for smartphones and tablets• Many widgets built with HTML5• Not compatible with Bootstrap
To use jQuery Mobile with a MVC project• Install with NuGet, selecting the jQuery Mobile MVC package• Adds bundles for the .js and .css jQuery Mobile files• Also adds a _Layout.Mobile.xxhtml view• And a view switcher view and controller to let the user switch between the
desktop and mobile views
jQuery Mobile
Same view on desktopand mobile device
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
jQuery Mobile makes extensive use of the HTML5 data-* attribute• Many values are defined for many types of elements
To transform a classic ul list into a touch-friendly list• Add a data-role attribute to the <ul> tag with a value of listview
To change a link into a buttonlike link• Add a data-role attribute to the <a> tag with the value button
jQuery Mobile and HTML5
<ul class="list" data-role="listview">
<a href="/ListingItem/Edit/1" data-role="button">Edit</a>
Without button role
With button role
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoOptional Demo: jQuery Mobile Your instructor might choose to demo ListPlus with jQuery mobile
• Open solution in C:\977\xx\Demo\Chapter 6\jQuery Mobile• A version of the ListPlus application without Bootstrap• Run in Opera Mobile Emulator, or Chrome in emulation mode
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction to jQuery
Ajax
Adapting to Mobile Devices
International Applications WebGrid and Chart
Chapter Contents
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Making an application international involves several modifications• Display views in different languages• Modify the display and input of numbers or dates• Change some other UI elements, such as images or even whole pages
Several techniques can be applied to MVC applications• Defining a different set of views for each language• Using resources to hold translated texts• Developing a custom system
– Useful when a database of translations already exists
Using resources is simpler• Based on standard .NET technologies• Easy to implement• Separate resource project makes it easy to process by external translators
The browser sends its culture name with each request• ASP.NET MVC can use it to determine the view to display
Globalizing Applications
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
.NET defines the CultureInfo class for globalization• In the System.Globalization namespace• Culture can be defined by its name, region-dependent (neutral) or not
• msdn.microsoft.com/en-us/goglobal/bb896001.aspx for full list
Each thread has two properties for culture info• CurrentCulture for dates and time, numbers, currency, sorting, casing …• CurrentUICulture to find culture-specific resources• Both are static properties of System.Threading.Thread class
Culture Basics
Culture name Descriptionen English (region-independent)en-US U.S. Englishen-UK U.K. Englishfr-FR France French
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
.NET resources are defined in XML files with extension .resx• Can contain strings, images, or other types of data• Visual Studio can generate classes to ease resource access
To add a resource file to a project• Select Add | New item• Select the Resource file template• Name resource file according to its culture
– MyResource.resx for a culture invariant resource file– MyResource.fr.resx for French resources (region-independent)– MyResource.fr-CH.resx for Swiss-French resources
Using a resource in code is done with the generated class • Each resource is a property
Resources
var msg = Resources.Models.ListingItemModel.PriorityQuantityError;C#
Dim msg = Resources.My.Resources.ListingItemModel.PriorityQuantityErrorVB
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toOptional Hands-On Exercise 6.3:
Making the ListPlus Application International
Optional Hands-On Exercise 6.3
41© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Introduction to jQuery
Ajax
Adapting to Mobile Devices
International Applications
WebGrid and Chart
Chapter Contents
42© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Many software tools exist to display grids and charts on HTML pages• Pure client-side with jQuery, like jqGrid• Or with some server-side support, like Telerik’s Kendo UI for ASP.NET MVC• Some are free, some must be purchased
ASP.NET MVC includes WebGrid and Chart helpers• Display grids and charts• No user input, although grid can be customized with specific HTML• Grids can be paginated, styled, columns sorted• Several types of charts, like columns, pies, lines …
Grid and Chart Tools
43© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Creating a WebGrid is a two-step process• Instantiate a WebGrid object, passing a collection to its constructor• Getting the grid HTML
WebGrid constructor has many optional parameters• Most common is the collection to be displayed in the grid
The grid is rendered with the GetHtml method• Returns the grid HTML• Has many optional parameters
Creating a WebGrid
@{var grid = new WebGrid(Model, canPage: false);
}
C#
@codeDim grid = New WebGrid(Model, canPage:=False)
End Code
VB
@grid.GetHtml()
44© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Default options for WebGrid• Display a column for each property in the source• Columns are sortable• Pagination is enabled with a page size of 10
All options can be customized• Grid parts can also be styled with CSS classes
Customizing a WebGrid
@(grid.GetHtml(columns: new List<WebGridColumn>{
new WebGridColumn { ColumnName = "Title", CanSort = true },new WebGridColumn { ColumnName = "Quantity" },new WebGridColumn { ColumnName = "Done" }
}))
C#
@(grid.GetHtml(columns:=New List(Of WebGridColumn) From{
New WebGridColumn With {.ColumnName = "Title", .CanSort = True},New WebGridColumn With {.ColumnName = "Quantity"},New WebGridColumn With {.ColumnName = "Done"}
}))
VB
45© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Chart class creates a chart• Constructor defines dimensions• AddSeries method adds series for the x-axis and the y-axis• Usually done in an action method in the controller
Chart creates an in-memory image• Returned to the client as an image with File helper
Generating Charts in Controllers
var chart = new Chart(600, 600);chart.AddSeries("Quantity", xValue: titles, yValues: quantities);
C#
Dim chrt = New Chart(600, 600)chrt.AddSeries("Quantity", xValue:=titles, yValues:=quantities)
VB
Collection for x-axis values
Collection for y-axis values
return File(chart.GetBytes(), "image/jpeg");C#
Return File(chrt.GetBytes(), "image/jpeg")VB
46© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
To render a chart on a page, simply use the <img> HTML element• Set the src attribute to the action method• Passing it the necessary parameters
Rendering a Chart on a Page
<img src="@Url.Action("Chart", new { id = 1 })" />
<img src="@Url.Action("Chart", New With {.id = 1})" />VB
C#
47© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 6.4: Displaying Data in a Grid and a Chart
Hands-On Exercise 6.4
48© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we have
Built highly interactive applications with the help of jQuery
Developed client-side UI elements with jQueryUI
Optimized page loading time with bundling and minification
Made client and server communicate smoothly with Ajax
Make an application mobile-friendly
Prepared applications for international markets
Used grids and charts to display data on pages
Chapter Summary
49© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 6-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Which techniques help minimize the size of pages sent to the browser?
What advantages does JSON have over XML?
Name some jQuery methods to make an Ajax call to the server
How would you transform a view into a mobile-specific view?
Which properties define the international options for a thread?
List some MVC HTML helpers that display structured data
Chapter Review
Building Professional Applications
Chapter 7
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, we will
Authenticate users and control access to action methods
Process unhandled exceptions with error handling
Add automatic unit tests to MVC applications
Create RESTful services with web API
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Controlling User Access Error Handling and Debugging
Unit Testing
Web API and Distributed Applications
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
All or parts of a website often need to be restricted to specific users• Or categories of users, named roles • Authentication is ensuring users are who they say they are• Authorization is ensuring users have access to the resources they require
Authorization in MVC uses the Authorize attribute• Can be set on an action method or on the controller
– If applied to the controller, applies to all action methods in the controller• Can also be set at the application level• User must be authenticated to access an Authorize resource
Authentication can use several mechanisms• Individual user accounts, from a custom database, or using existing accounts
from Facebook, Twitter, Google, Microsoft …• Organizational accounts with Active Directory or Office 365• Windows authentication
Authentication and Authorization
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The Authorize attribute is a filter• Can be applied to a single method
• Or to a controller
• Or added as a global filter in the FilterConfig class in App_Start
The Authorize Attribute
[Authorize]public ActionResult Index()
C# <Authorize>Public Function Index() As ActionResult
VB
[Authorize]public class AdminController : Controller
C#
<Authorize>Public Class AdminController
Inherits System.Web.Mvc.Controller
VB
filters.Add(new AuthorizeAttribute());C#
filters.Add(New AuthorizeAttribute())VB
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Authorization can be limited to a set of users or roles• With the Users and Roles properties• Take a comma-separated list of users or roles
When the Authorize attribute is applied to the whole application or a controller, no action method can be called anonymously• AllowAnonymous attribute allows anonymous access to action or controller• For example, the login view!
Authorize and AllowAnonymous Attribute
[Authorize(Roles="Admin,SuperAdmin")]C#
<Authorize(Roles:="Admin,SuperAdmin")>VB
[AllowAnonymous]public class AccountController : Controller
C#
<AllowAnonymous>Public Class AccountController
Inherits System.Web.Mvc.Controller
VB
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Authentication in ASP.NET relies on ASP.NET Identity• Replaces membership in previous versions• Applies to MVC, Web Forms, Web API and more
ASP.NET Identity• Extensible: Can define profile data for the user (i.e., birth date)• Persistence control: SQL Server by default but can be customized• Connects to social login providers such as Facebook, Google …• Supports claims-based authentication• Based on OWIN (Open Web Interface for .NET)
– Standard to decouple server and application
ASP.NET Identity
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Can use own storage, or connect to social login providers
Based on two classes• IdentityUser: The user, essentially a username• UserManager: Defines operations that can be done on user
Default behavior is to store user data in a SQL Server database• Using Entity Framework code-first• Can be entirely customized
– Adding custom user data– Changing the store location or provider
Individual User Accounts
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Initial request has no authorization cookie• After login, requests and responses have an authorization cookie
The Authorization Cookie
Request action marked Authorize
Call requested action
YesCall Login action
No
Put authorization cookie in response
Authorization cookie in request?
Yes
Login view
Login successful?No
Redirect to requested action
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Open standards for authorization• Log in using existing accounts on trusted sites (providers)• Facebook, Twitter, LinkedIn, Windows Live implement OAuth• Google, Yahoo implement OpenID
OAuthWebSecurity class hides most differences between protocols and providers• Interacts with the open-source DotNetOpenAuth library• Has methods to register with providers• OAuth requires authorization ID from provider• To register a Facebook client
OAuth and OpenID
OAuthWebSecurity.RegisterFacebookClient(appId: "xxxxxxxxxxxxxx",appSecret: "yyyyyyyyyyyyy");
C#
OAuthWebSecurity.RegisterFacebookClient(appId:="xxxxxxxxxxxxxx",appSecret:="yyyyyyyyyyyyy")
VB
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoIndividual Account Authentication Your instructor will demo the standard template for individual account
authentication• Create a new MVC project with Individual User Accounts• Open IdentityModel in the Models folder
– Note the IdentityUser- and IdentityDbContext-derived classes• Open the AccountController
– Note the UserManager property and its use in the constructor– The UserManager property is used to do operations on the user
• Run, register a new account– Look for the database created by default in the App_Data folder– DefaultConnection connection string defined in Web.config
• Open Startup.Auth in App_Start– Note the LoginPath– Uncomment last line to enable Google authentication
• Run and login with a Google account if you have one and have an Internet connection
Completed application C:\977\CS\Demo\Chapter 7\IndivitualAccountAuthentication
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 7.1: Adding Authentication and Authorization
Hands-On Exercise 7.1
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Other authentication options are available when creating a new project• Windows authentication• Organizational accounts
Windows authentication• Users are authenticated with their Windows login• No need for an account controller• An option is added in Web.config:
Organizational accounts• Authentication is done with
Active Directory (cloud or on premises) or Office 365
Other Authentication Options
<authentication mode="Windows" />
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Password is sent as clear text in the Login page• Should use SSL to encrypt requests and responses
– Done in bonus section of last exercise• Add RequireHttps attribute to the Account controller• Should also set it on all-protected action methods or controllers
Preventing potential attacks on the website• Install the AntiXSS NuGet package to prevent cross-site attacks
– Encoding all HTML and JavaScript• Prevent cross-site forgery
– Add a hidden token in pages with @Html.AntiForgeryToken()– Add the ValidateAntiForgeryToken attribute to action POST methods– Done by the default Visual Studio templates
More Security Options
SSL = Secure Sockets Layer
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Controlling User Access
Error Handling and Debugging Unit Testing
Web API and Distributed Applications
Chapter Contents
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
An exception filter implements the IExceptionFilter interface • Defines a single method, OnException• Runs when an unhandled exception occurs where the attribute is applied
– An unhandled exception is an exception that is not caught by a try-catch
MVC has a built-in implementation, HandleErrorAttribute• ExceptionType property specifies the exceptions that will be handled• View property specifies the view to display—Error.xxhtml by default• The view receives a model of type HandleErrorInfo
Like other filters, an exception filter can be applied to an action method• Often set in global.asax so that it applies to all actions in all controllers• VS templates define a global HandleError filter and Error.xxhtml view
Handling Exceptions With the HandleError Attribute
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Global filters are defined in FilterConfig class, in App_Start folder• RegisterGlobalFilters is called from global.asax• Other filters can be registered there
For the HandleError attribute to work, custom errors must be set• In the Web.config file
• mode attribute values can be– Off: A standard error page is displayed (“yellow page”)– On: Custom error pages are displayed– RemoteOnly: Custom error pages are displayed if browser is not on the
same machine as the web server; a standard error page is displayed otherwise
Using Custom Errors
<system.web><customErrors mode="On"/>
Set the value in the Web.config file located at the root of the website, not in the Views folder
filters.Add(new HandleErrorAttribute())
18© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The HandleErrorInfo class is passed as the model to the error view• ActionName and ControllerName properties• Exception property gives access to the exception details
The code in the error handling view must be tested carefully• If an exception occurs, the default yellow page will be displayed
HandleErrorInfo Class
Exception <b>@Model.Exception.Message</b> <br />In action method <b>@Model.ActionName</b>of <b>@Model.ControllerName</b> controller
19© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 7a: The HandleErrorAttribute
1. Open and build the Do Now 7a starting point inC:\977\xx\Do Nows\Do Now 7a-Start Point
2. Open the Index action method of the Home controller• It does an integer division by zero that raises an exception
3. Run the application out of Visual Studio with <Ctrl><F5>• A yellow page is displayed
4. Open the Web.config file located at the application root; add the following line below the <system.web> tag
5. Open the Error.xxhtml view in the Shared folder
6. Add a model (C#) or ModelType (VB) statement for HandleErrorInfo
7. Add the following line after the h2 element
8. Run the application using <Ctrl><F5> and notice the custom error page
<customErrors mode="On"/>
@Html.Raw(Model.Exception.StackTrace.Replace("\n", "<br/>"))
20© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Controlling User Access
Error Handling and Debugging
Unit Testing Web API and Distributed Applications
Chapter Contents
21© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
With unit testing, individual units of code are tested• Typically classes, or individual methods
Test-driven development (TDD) cycle takes it one step further• Work on small software units• Start by writing a test that defines an expected behavior• Test must fail, as implementation is not done yet• Write implementation until test succeeds• Refactor code, checking that test still succeeds • Repeat on each software unit until application is complete
Automating tests is one of the main selling arguments of MVC• Supports TDD in ASP.NET MVC applications• Also supports standard unit testing• Select the Create a unit test project checkbox when creating a new MVC
project
More on TDD and unit testing
Unit Testing and Test-Driven Development
511®
Course 511, .NET Best Practices and Design Patterns
22© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Unit testing is done on class libraries• In MVC, testing focuses on controllers and models
– Test code takes the place of views
An MVC application must not “know” it is being tested• Tests are written in a class library project• References the MVC application• Instantiates controllers and calls action methods
Test project is run by a test application• We’ll use Visual Studio Tests• Alternatives such as NUnit exist
Unit Testing MVC Applications
Controller
View
TestsVisual Studio
Testsor NUnit
23© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Visual Studio Tests loads the tests class library• Looks for specific attributes on classes and methods• Instantiates classes and calls methods depending on those attributes• NUnit works the same way; attribute names are different
Main Visual Studio Tests attributes
Running Tests
Attribute DescriptionTestClass Class is included in testsTestMethod Method is called during testsClassInitialize Method called when class is loadedClassCleanup Method called when class is unloadedTestInitialize Method called before each test in classTestCleanup Method called after each test in class
24© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A test method has three phases• Arrange: Instantiate the controller and other resources• Act: Call the method being tested• Assert: Test the result values
Test Methods (C#)
[TestClass]public class HomeControllerTest{
[TestMethod]public void Index(){
// Arrangevar controller = new HomeController();
// Actvar result = controller.Index() as ViewResult;
// AssertAssert.AreEqual(result.ViewName, "Index");
}}
C#
Cast result to give access to ViewName property
25© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Test Methods (VB)
<TestClass>Public Class HomeControllerTest
<TestMethod>Public Sub Index()
Dim controller = New HomeController()
Dim result = DirectCast(controller.Index(), ViewResult)
Assert.AreEqual("Index", result.ViewName)End Sub
End Class
VB
Cast result to give access to ViewName property
26© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Assert class has many static methods to test the results• If any Assert fails, the method is marked as “not passed”• Red light-green light
Assert
Assert Method DescriptionAreEqual/AreNotEqual Values are equal/are not equal
AreSame/AreNotSame Two variables reference the same object/different objects
IsTrue/IsFalse Condition is true/falseIsInstanceOfType/IsNotInstanceOfType Object is/is not an instance of type
IsNull/IsNotNull Object is/is not null
27© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Tests are done from within Visual Studio
Tests and Visual Studio
Green light
Red light
Test result details
28© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Do NowDo NowDo Now 7b: Adding Unit Testing to ListPlus
1. Open and build the Do Now 7b starting point inC:\977\xx\Do Nows\Do Now 7b-Start Point
2. Open the HomeControllerTest class in the Controllers folder of the ListPlus.Web.Test project and try to understand the code
3. Select TEST | Run | All Tests and look for the results in Test Explorer• One test should fail
4. Select TEST | Debug | All Tests to try and understand why the test fails• The code should break on the call to Assert
5. Fix the code in the Index method of the HomeController class in the ListPlus.Web project• Pass the view name to the View method
6. Run all tests again• They should succeed
29© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Testing can be much more complex• Controller methods call service methods• Service methods call the repository and need the database
A good practice is to test each component individually• Unit testing• The service layer can have its own test project• MVC tests must focus on testing the controllers
The Mock pattern replaces a component by a fake component• Designed specifically for testing• Can use software tools such as Moq• Installed with NuGet
Testing Complex Applications
30© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoTesting With Moq Your instructor will demo a test application with Moq
• Open the previous completed Do Now in C:\977\xx\Do Nows\Do Now 7b-Completed
• Moq has been added to the ListPlus.Web.Test project• Open the ListingControllerTest class• Points to note
– A class variable named listings holds test data– A Mock object is initialized with IListingService for generic type– The Mock object is passed to the ListingController, taking the place
of the expected IListingService parameter
31© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Controlling User Access
Error Handling and Debugging
Unit Testing
Web API and Distributed Applications
Chapter Contents
32© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
A distributed application has components located on different computers• Communicating across a network• Typically the Internet or an intranet
Web Services allow components to communicate over the Internet• Clients call methods in servers• Several protocols available such as SOAP, WSDL• Web API is a lightweight alternative
Web API is now part of ASP.NET• REST-based: Uses the URL to define the requested resource• Leverages the HTTP• Easy to use by any client that can make an HTTP request• Response data can be XML or JSON
Distributed Applications
SOAP = Simple Object Access ProtocolWSDL = Web Services Description Language
2601®
For more about WCF and web API, see Course 2601, WCF, Web API, and SignalR Services for .NET
33© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Web API also uses controllers• Classes based on a different base class: ApiController• Not specific to MVC applications: Can be used in Web Forms applications• Action methods return an object, not an ActionResult• Returned object is serialized in XML or JSON and passed to the client
Each action method is mapped to an HTTP verb• Either by name
– Action method name includes verb name– Get, GetList, or PleaseGetTheList map to the GET verb
• Or with an attribute such as HttpGet
HTTP verbs are mapped to logical actions• GET to read data• POST to add data• PUT to modify data• DELETE to delete data
Web API
34© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In Add controller dialog, select Empty API controller• Other templates create controller with existing action methods
Add methods that map to HTTP verbs
Creating a New Web API Controller
public class EmployeeController : ApiController{
public List<EmployeeModel> GetList(){
return _employees;}
C#
Public Class EmployeeControllerInherits ApiController
Public Function GetList() As List(Of EmployeeModel)Return _employees
End Function
VB
Maps to HTTP GETBase class is
ApiControllerReturn data to client
35© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Web API uses a specific route table• Initialized in WebApiConfig in App_Start folder• Can add and customize routes like MVC routes• No action name in the route
– Method is determined by combination of controller name plus HTTP verb
Web API Route Table
config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
);
C#
config.Routes.MapHttpRoute( _name:="DefaultApi", _routeTemplate:="api/{controller}/{id}", _defaults:=New With {.id =
RouteParameter.Optional} )
VB
Default prefix for URLs http://localhost:6666/api/Employee/2
36© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Web API clients can be any type of application• Must be able to make HTTP request and process returned XML or JSON• .NET or non-.NET• Data format is defined in the client request
– With the Accept parameter in the HTTP request header
Web clients can make calls with Ajax• Using jQuery, with the multipurposes $.ajax• Or with specific helper: $.get, $.post, or $.getJSON
Windows clients can use the WebClient class• Or the HttpClient found in the ASP.NET Web API Client Libraries
downloadable from NuGet
Web API Clients
37© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
DemoDemoWeb API Server and Web Ajax Client Your instructor will demo a web API server application
• In C:\977\xx\Demo\Chapter 7\WebAPI• EmployeeApiController has web API methods for CRUD operations• Index view has jQuery code to make Ajax call to GetList method• Run with <Ctrl><F5> and click the List Employees button• Use Fiddler to view and/or make requests
38© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 7.2: Building a Web API Controller
Hands-On Exercise 7.2
39© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, you have
Authenticated users and controlled access to action methods
Processed unhandled exceptions with error handling
Added automatic unit tests to MVC applications
Created RESTful services with web API
Chapter Summary
40© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 7-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Which attribute restricts access to an action method to authenticated users?
How would you handle exceptions in an ASP.NET MVC application?
Which attributes are applied to a class or a method to include them in tests?
Name the HTTP verbs used to implement CRUD operations
Chapter Review
Application Deployment
Chapter 8
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, you will
Prepare an application for deployment
Deploy the ASP.NET MVC application on an IIS web server
Deploy in the Azure cloud
Chapter Objectives
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Preparing and Deploying to IIS Deploying to Windows Azure
Chapter Contents
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Application deployment must be prepared• Compiling all views to detect errors• Removing debugging information• Cleaning up Web.config
Deployment can be done on an IIS server• Or in the cloud—Windows Azure, for example• Target staging or production server• Done with Visual Studio Publish wizard
Preparing Deployment
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Visual Studio defines two configurations by default• Debug and Release• New configurations can be added in BUILD | Configuration Manager
Each configuration has a Web.config transformation file• Named after the configuration• Has instructions to modify settings in Web.config• Is processed when building the project
In Web.Release.config• To remove debug attribute from compilation element
Modifying Web.config
<system.web><compilation xdt:Transform="RemoveAttributes(debug)" />
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Use BUILD | Publish on the web project• Can define several profiles• Each profile sets destination
Web Deploy includes instructions to configure IIS• Databases can also be included in the deployment package
Publishing the Application
Publish method Description
Web Deploy Publish directly in IIS—Must have administrative rights
Web Deploy Package Create package that can be imported in IISFTP Publish to FTP folderFile System Publish to local directory or network shareFPSE FrontPage Server Extensions (legacy)
FTP = File Transfer Protocol
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
IIS 7 supports ASP.NET MVC natively• Unless application pool is configured in classic mode, for IIS 6 compatibility
IIS 6 and IIS 7 in classic mode need some configuration• Rely on file extension to process requested URLs• Web Forms .aspx will be routed to ASP.NET• But MVC doesn’t use file extensions
Two main solutions• Add a pseudo file extension to controllers in the routing table, and map that
extension to ASP.NET in IIS– Like ListPlus/Listing.mvc/List
• Use a wildcard mapping to ASP.NET in IIS– All requests will go through ASP.NET, even .html files
• See http://www.asp.net/learn/mvc/tutorial-08-cs.aspx for more details
IIS and ASP.NET MVC Applications
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In your Exercise Manual, please refer toHands-On Exercise 8.1: Deploying the Application
Hands-On Exercise 8.1
9© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Preparing and Deploying to IIS
Deploying to Windows Azure
Chapter Contents
10© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Windows Azure is the Microsoft offering for the Cloud• Websites• Virtual machines• Storage• Mobile and cloud services• SQL Databases• And more
Can deploy ASP.NET MVC applications to Windows Azure• Using Web Deploy• Azure provides a publish profile that can be imported in Visual Studio
Windows Azure
11© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
On manage.windowsazure.com• Must have an account
Creating a Windows Azure Website
12© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Download the publish profile and save to a file
Getting the Publish Profile
13© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Import profile into Visual Studio Publish wizard
Publishing to the Azure Website
14© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Connection data is automatically set
Setting Connection Data
15© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
The wizard modifies the connection strings as appropriate• To use a SQL Database in Azure• Database must be deployed in Azure
Modifying the Connection Strings
16© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Application now runs in Azure!
Running in Azure
17© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 8-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this chapter, you have
Prepared your application for deployment
Deployed the ASP.NET MVC application on an IIS web server
Deployed in the Azure cloud
Chapter Summary
Course Summary
Chapter 9
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. 9-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
In this course, you have
Built and deployed secure, scalable applications with ASP.NET MVC
Generated HTML dynamically with Razor view, partial views, and view helpers
Created a loosely coupled model with the Entity Framework and dependency injection
Developed application controllers and action filters
Structured applications with areas and URLs with routing
Built and validated forms with standard and custom HTML helpers
Designed rich client and mobile UIs with Ajax, jQuery, and jQueryUI
Secured applications with authentication and third-party providers
Created RESTful services with web API
Course Summary
Answers to Review Questions
Appendix A
2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 1 Review
To which layer do the view and controller belong?
The presentation layer
Name three Visual Studio templates for MVC applications
Empty, Basic, Internet, Intranet
What is the role of the controller in an MVC application?
Receives client requests, calls the model, selects the view
How are classes named in controllers?
With a Controller suffix
Name some HTTP verbs
GET, POST
What are the main advantages of ASP.NET MVC over Web Forms?
Better structured, full control of HTML, ready for TDD
3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 2 Review
Name different ways to pass data from controller to view
ViewBag, ViewData, model
Write a statement that sets the model type to Person in a view
C#: @model Person – VB: @ModelType Person
How do you introduce a code block with Razor in C# or VB?
C#: @{...} – VB: @Code...End Code
Name the command to render the body content in a layout view
@RenderBody
Where would you set the name of the layout view in a project?
In the _ViewStart view
Which technologies help factorize parts of view?
View helpers, partial views
4© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 3 Review
What is the role of the model in the MVC architecture?
Implement the business logic
Name layers that help structure the model
Service layer, repository or data access layer
Which class is the entry point to access data with the Entity Framework?
DbContext
How would you break dependencies between layers in the model?
Programming on interfaces and using dependency injection
To which code element are these database items mapped with an ORM?
Table ClassColumn Property
Row ObjectRelation Collection
5© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 4 Review
Which interface must a controller implement?
IController
What is the return type of an action method?
ActionResult
How does MVC find the controller to instantiate from its name?
With a controller factory
Name some built-in filters
Authorize, HandleError, RequireHttps, OutputCache
What are the two main responsibilities of the routing system?
Inbound routing and outbound routing
How would you structure an MVC application that has many controllers?
Using areas
6© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 5 Review
Write the Razor code that generates a form in a view
@using (Html.BeginForm)...
Name some HTML helpers for input fields
TextBoxFor, CheckBoxFor, HiddenFor
Which class is used to generate a drop-down list?
SelectList with the DropDownList HTML helper
Which language feature is used to create a custom HTML helper?
Extension methods
How can you know if model binding succeeded?
Testing the ModelState.IsValid property
Write the code that limits input of a Name property to 20 characters
[StringLength(20)] string Name { get; set; }
7© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 6 Review
Which techniques help minimize the size of pages sent to the browser?
Bundling and minification
What advantages does JSON have over XML?
More concise, same format as JavaScript objects
Name some jQuery methods to make an Ajax call to the server
getJSON, ajax, get, post
How would you transform a view into a mobile-specific view?
Adding mobile in the view name
Which properties define the international options for a thread?
CultureInfo, UICultureInfo
List some MVC HTML helpers that display structured data
WebGrid, Chart
8© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. A-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.
Chapter 7 Review
Which attribute restricts access to an action method to authenticated users?
Authorize
How would you handle exceptions in an ASP.NET MVC application?
With a HandleError filter
Which attributes are applied to a class or a method to include them in tests?
TestClass and TestMethod
Name the HTTP verbs used to implement CRUD operations
POST, GET, PUT, DELETE