Course 977 Building Web Applications With ASP.NET MVC

Course 977 Building Web Applications With ASP.NET MVC 977/CN/H.2/410/H.1 © LEARNING TREE INTERNATIONAL, INC. All rights reserved. All trademarked ...
37 downloads 0 Views 2MB Size
Course 977

Building Web Applications With ASP.NET MVC

977/CN/H.2/410/H.1

© 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.

Acknowledgments The author would like to acknowledge the following for their contributions to this course:

 Stacy Diehl  Kevin Rattan  All the instructors who contribute with bug reporting and enhancement suggestions

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Course Objectives 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 API = application programming interface HTML = hypertext markup language

REST = representational state transfer

UI = user interface URL = uniform resource locator

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Course Contents 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Prerequisites  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 – – – –

 Inform your instructor if you don’t meet these prerequisites

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

®

503 419

Course Exercises  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 study at home – A list of recommended books

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

C# code

Exercise starting point Finished exercises VB code

Software Used  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Questions  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter 1

Introducing ASP.NET MVC

Chapter Objectives 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

HTTP = Hypertext Transfer Protocol MVC = Model View Controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-2

Chapter Contents

 The MVC Design Pattern  MVC Workflow and Projects  The HTTP Protocol  Web Forms and MVC

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-3

MVC and Multitier Applications  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

WPF = Windows Presentation Foundation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-4

MVC and Multitier Applications

Controller

Model

View

Presentation

Business

Data

Database

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-5

One ASP.NET  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

This section has templates from the previous version

One ASP.NET – New in Visual Studio 2013

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-6

ASP.NET Project Templates Empty ASP.NET project

ASP.NET MVC application with some views

Select authentication options Select frameworks to configure

Add unit tests

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-7

AdaptaLearn™ Enabled  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)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-8

Using AdaptaLearn™

Do Now

 Let’s try it now 1. Launch AdaptaLearn by double-clicking its icon on the desktop 2. 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 menu 4. Use to change the font size as desired 5. If your screen is small or you want to maximize the AdaptaLearn window, use to toggle back and forth 6. A folded area is introduced in blue text – Click the text to see how folds work 7. A copy-and-paste area is in a blue box – Hover over the box (but don’t click on it) and press

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-9

Hands-On Exercise 1.1

In your Exercise Manual, please refer to Hands-On Exercise 1.1: Building a Simple MVC Application

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-10

Chapter Contents

 The MVC Design Pattern

 MVC Workflow and Projects  The HTTP Protocol  Web Forms and MVC

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-11

The Controller Is the Conductor  The client makes a request by • Clicking a link • Posting a form • Making an Ajax call

More on posting and Ajax in later chapters

 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 JSON = JavaScript Object Notation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-12

MVC Request and Response

The controller asks the model to process the request

Request Response

1

Controller

6

2

Model

3 5

4

View

The controller calls the view to generate the output

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-13

Controller and Action Methods  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 http://server/Home/Index C#

The return view is named after the action method by default

public class HomeController : Controller { public ActionResult Index() { return View(); } Public Class HomeController } Inherits System.Web.Mvc.Controller Function Index() As ActionResult Return View() End Function End Class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

1-14

Views and View Engines  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

ASPX = Active Server Page Extended File

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-15

MVC Projects in Visual Studio  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 for each controller • Views are in a folder named after the controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-16

Chapter Contents

 The MVC Design Pattern  MVC Workflow and Projects

 The HTTP Protocol  Web Forms and MVC

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-17

The HTTP Protocol  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)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-18

HTTP Verbs  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 in browser XML = extensible markup language

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-19

Do Now 1a: Exploring HTTP With Fiddler

Do Now

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 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-20

Exploring HTTP With Fiddler Illustrated

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Do Now

1-21

HTTP Requests and Responses  HTTP request GET verb with requested URL Requested data type User-Agent identifies the requesting browser

A POST request would have some data in the body

 HTTP response Response code indicates success or failure Returned content data type Returned data, displayed by the browser

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Blank line separates header from body

1-22

Chapter Contents

 The MVC Design Pattern  MVC Workflow and Projects  The HTTP Protocol

 Web Forms and MVC

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-23

Microsoft Technologies for Web Applications  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-24

ASP.NET Web Forms and MVC  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 TDD = test-driven development

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-25

Do Now 1b: Designing Pages With No Designer

Do Now

1. Open the Do Now 1b starting point • This is the finished HelloMVC solution from the last exercise 2. Press 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 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 7. Add some text to the Index.cshtml file and save it 8. Refresh the Page Inspector to see changes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-26

The Course Case Study

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-27

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-28

Chapter Review 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?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1-29

Chapter 2

Views and the Razor View Engine

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-2

Chapter Contents

 Views, ViewBag, and Models  The Razor Syntax  Structuring Views With Layouts  Partial Views and View Helpers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-3

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 …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-4

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 public ActionResult Index() { return View(); }

C#

Function Index() As ActionResult Return View() End Function

VB

• The following code has the same result public ActionResult Index() { return View("Index"); }

C#

Function Index() As ActionResult Return View("Index") End Function

 The view is located in a folder named after the controller • Views\Home for the Home controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-5

VB

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

ViewBag is passed from controller to view

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-6

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: ViewBag.Hello = "World"

C#

ViewBag.Hello = "World"

VB

 Wrapper around the ViewData dictionary • Same result as previous code snippet: ViewData["Hello"] = "World";

C#

ViewData("Hello") = "World"

 Using the ViewBag • In the controller ViewBag.Hello = "World"; return View("Index");

C#

VB

VB

ViewBag.Hello = "World" Return View("Index")

• In the view Hello @ViewBag.Hello

Razor

Displays Hello World

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-7

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-8

Using the Model in the Controller  The model classes are often properties-only classes C#

public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }

Public Class Property Property Property End Class

Person Id As Integer Name As String Age As Integer

VB

 The action method gets the model and passes it to the view var person = new Person { Id = 1, Name = "Andrew", Age = 10 }; return View(person);

Dim thePerson As New Person With {.Id = 1, .Name = "Andrew", .Age = 10} Return View(thePerson)

C#

VB

 Usually, the model is obtained from a call to a service layer • Or generated from classes retrieved from the service layer

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-9

Using the Model in the View

Demo

 The view uses the properties of the model Name: @Model.Name
Age: @Model.Age

 Add a directive at the top of the view to strongly type the model @model ViewDemo.Models.Person

C#

@ModelType ViewDemo.Person

VB

 Your instructor will demonstrate passing data between the controller and the view • Open the solution in C:\977\xx\Demo\Chapter 2\PassingData

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-10

Chapter Contents

 Views, ViewBag, and Models

 The Razor Syntax  Structuring Views With Layouts  Partial Views and View Helpers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-11

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 Name: @Model.Name


Output as is in the HTML flow

Output of ToString() on the expression is sent to the HTML flow

Output as is in the HTML flow

• Resulting output if value of Name property is Andrew: Name: Andrew


© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-12

Razor Expressions  Special characters can lead to unexpected results • For example: Your age next year: @Model.Age+1

• Output is: Your age next year: 10+1

Razor “thinks” expression is finished

 A Razor expression can be put between parentheses • This syntax gives the expected result: Your age next year: @(Model.Age+1)

• Output: Your age next year: 11

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-13

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 (C#) or List(Of Person) (VB): C#

Braces must be used in C#, even for one line instructions C# switches back to HTML output

@foreach (var person in Model) { @person.Name - @person.Age }

VB

VB needs a hint with a @ LINQ = Language Integrated Query

@For Each person In Model @@person.Name - @person.Age Next

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-14

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: C#

@{ var persons = Model;

} @foreach (var person in persons) { @person.Name - @person.Age } VB

@Code Dim persons = Model End Code @For Each person In persons @@person.Name - @person.Age Next

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-15

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 or C#

@foreach (var person in Model) { Person name: @person.Name
} VB @For Each person In Model @Person name: @person.Name
Next

• Or use @: C#

@foreach (var person in Model) { @:Person name: @person.Name
} @For Each person In Model @:Person name: @person.Name
Next

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

2-16

Hands-On Exercise 2.1

In your Exercise Manual, please refer to Hands-On Exercise 2.1: Creating the Case Study Project

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-17

Chapter Contents

 Views, ViewBag, and Models  The Razor Syntax

 Structuring Views With Layouts  Partial Views and View Helpers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-18

Layout Pages  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 Header and menu, common to all pages

Content specific to this page

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-19

Common HTML Markup  Common markup belongs in a layout view • Specific markup stays in the view

Common to all pages

Index Hello Layout! Specific to this page

 Page-specific content is replaced by a placeholder in the layout view

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-20

Layout and View  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 Index.cshtml

@{ Layout = "~/Views/Shared/_Layout.cshtml"; } Hello Layout!

_Layout.cshtml

Title @RenderBody()

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-21

ViewStart  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.cshtml

@{ Layout = "~/Views/Shared/_Layout.cshtml"; } Index.cshtml

Hello Layout!

_Layout.cshtml

Title @RenderBody()

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-22

Layout Sections  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 Index.cshtml

Hello Layout! @section footer { This is the footer }

Section name

_Layout.cshtml

@RenderBody() @RenderSection("footer", false) Section is not required

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-23

Section Default Value  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 _Layout.cshtml

@RenderBody() @RenderSection("footer", false) @if (!IsSectionDefined("footer")) { @:This is the footer from the layout }

Will only be rendered if footer section is not defined in view

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-24

Hands-On Exercise 2.2

In your Exercise Manual, please refer to Hands-On Exercise 2.2: Layout Pages

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-25

Chapter Contents

 Views, ViewBag, and Models  The Razor Syntax  Structuring Views With Layouts

 Partial Views and View Helpers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-26

Factorizing Parts of Views  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-27

View Helper Methods  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 @Display("Hello") ASP.NET @Display("MVC") @helper Display(string text) { @text }

C#

@Display("Hello") ASP.NET @Display("MVC") @helper Display(text As String) @@text End helper

C:\977\xx\Demo\Chapter 2\ViewHelper

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-28

VB

Partial Views  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-29

Using a Partial View  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 Index.cshtml

This is the main view
Partial: @Html.Partial("Time", DateTime.Now)

Second parameter is the model Time.cshtml

@model DateTime The time is: @Model.ToShortTimeString()

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-30

HTML Helpers  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 Forms and custom helpers are covered in Chapter 5

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-31

Generating Links in a View  The ActionLink HTML helper generates a link in a view • Produces a standard element using information from the routing table • Several overloads can be used • In the Home controller @Html.ActionLink("Display", "Display") Display @Html.ActionLink("People list", “List", "People") People list

• Parameters are passed in an anonymous object @Html.ActionLink("Display", "Display", new { name = "Fred" }) Display Routing is covered in Chapter 4 C:\977\xx\Demo\Chapter 2\Links

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-32

Hands-On Exercise 2.3

In your Exercise Manual, please refer to Hands-On Exercise 2.3: Styling and Simplifying the View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-33

The View Infrastructure  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-34

WebViewPage Class  The WebViewPage class has many properties • Can be found in the documentation at msdn.microsoft.com/library Property

Description

Context

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 elements

Model

The model associated with a page

Request, Response, Server, Session

Give access to the corresponding ASP.NET objects

TempData

A dictionary to store data during a request

Url

URL of the page

ViewBag, ViewData

Dynamic object or dictionary to share data between the view and the controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-35

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-36

Chapter Review 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?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

2-37

Chapter 3

The Model

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-2

Chapter Contents

 Model Tier Architecture  Accessing Data With the Entity Framework  Repository and Data Query  Service and Business Logic  Decoupling Layers With Dependency Injection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-3

ASP.NET MVC Architecture and the Model  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!

Request Response

Controller

Model

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-4

From Model to Database  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 Model

Controller

Business logic

Data access

Database

View

WCF = Windows Communication Foundation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-5

Layers in the Model  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 Controller

Service

Repository

Database

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-6

Data Classes  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

Controller

View model classes

Entity classes

Service

Repository

Database

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-7

Chapter Contents

 Model Tier Architecture

 Accessing Data With the Entity Framework  Repository and Data Query  Service and Business Logic  Decoupling Layers With Dependency Injection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-8

Data Access Technologies  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 .NET code

Relational database

Class

Table

Property

Column

Object

Row

Collection

Relation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-9

Entity Framework  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 SQL Server Edition

Description

Standard, BI, Web, Enterprise

Enterprise on premises

Express

Free scaled-down edition

Azure

SQL Server in the cloud

LocalDB

Included in VS for development

Compact

Embedded on devices

DBMS = database management system

BI = Business Intelligence

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-10

Entity Framework Modes  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-11

Hands-On Exercise 3.1

In your Exercise Manual, please refer to Hands-On Exercise 3.1: Adding Entity Framework to the Case Study

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-12

Entity Framework-Generated Files  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: public partial class ListPlusEntities : DbContext Partial Public Class ListPlusEntities Inherits DbContext

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

C#

VB

3-13

Chapter Contents

 Model Tier Architecture  Accessing Data With the Entity Framework

 Repository and Data Query  Service and Business Logic  Decoupling Layers With Dependency Injection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-14

CRUD Operations in the Repository  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 C#

public List List() { Derived class combines using (var db = new ListPlusEntities()) database name and Entities { return db.Listings.ToList(); } } VB Public Function List() As List(Of Listing) Using db = New ListPlusEntities Return db.Listings.ToList() Using block ensures End Using DbContext is disposed End Function

CRUD = Create, Retrieve, Update, Delete

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-15

Reading a Single Entity  SingleOrDefault returns a single entity C#

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(); } Public Function Read(id As Integer) As Listing } Using db = New ListPlusEntities Dim q = From lst In db.Listings Where lst.Id = id Select lst Return q.SingleOrDefault() End Using End Function

VB

• If the criteria are the primary key, code can be simplified to return db.Listings.Find(id);

C#

Return db.Listings.Find(id)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

3-16

Adding an Entity  Modifications are done on the DbSet collections • And committed to the database with the SaveChanges method  To add a new item C#

public void Add(Listing listing) { using (var db = new ListPlusEntities()) { db.Listings.Add(listing); db.SaveChanges(); } Public Sub Add(listing As Listing) } Using db = New ListPlusEntities db.Listings.Add(listing) db.SaveChanges() End Using End Sub

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

3-17

Updating an Entity  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 C#

public void Update(Listing listing) { using (var db = new ListPlusEntities()) { db.Listings.Attach(listing); db.Entry(listing).State = EntityState.Modified; db.SaveChanges(); VB Public Sub Update(listing As Listing) } Using db = New ListPlusEntities } db.Listings.Attach(listing) db.Entry(listing).State = EntityState.Modified db.SaveChanges() End Using End Sub

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-18

Deleting an Entity  To delete an existing entity • Retrieve the entity • Remove it from the entities collection • Save the changes C#

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

VB

Dim lst = db.Listings.Find(listing.Id) db.Listings.Remove(lst) db.SaveChanges() End Using End Sub

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-19

Hands-On Exercise 3.2

In your Exercise Manual, please refer to Hands-On Exercise 3.2: Programming the Repository

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-20

Loosely Coupled Applications  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 IListingRepository List Add Update Delete

ListingRepository List Add Update Delete

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-21

Chapter Contents

 Model Tier Architecture  Accessing Data With the Entity Framework  Repository and Data Query

 Service and Business Logic  Decoupling Layers With Dependency Injection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-22

The Service Layer  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

Controller

View model classes

Entity classes

Service

Repository

Database

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-23

Data, Entity, and View Models  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 MVC application

View model

Entity Framework

Application code

Entity model

Database

Entity Framework

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Data model

3-24

View Model Classes  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-25

Service Classes and Interfaces  The service layer should expose its functionality through interfaces • Just like the repository layer • Necessary for implementing dependency injection  Steps to retrieve data 1. 2. 3. 4. 5. 6. 7. 8.

The controller calls a method in the service Service calls one or more methods in the repository Repository methods use Entity Framework to get data from the database Repository returns entities to the service Service implements the business rules and processes the returned entities Service builds a view model and returns it to the controller Controller selects the view and passes the view model to the view The view uses the view model to build HTML

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-26

Project References  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 View models

Entities

Service

Repository

Controllers views

Reference

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-27

Hands-On Exercise 3.3

In your Exercise Manual, please refer to Hands-On Exercise 3.3: Adding the Service Layer

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-28

Chapter Contents

 Model Tier Architecture  Accessing Data With the Entity Framework  Repository and Data Query  Service and Business Logic

 Decoupling Layers With Dependency Injection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-29

Tight Coupling  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 _listingService = new ListingService(); _listingService = New ListingService()

C#

VB

• Likewise, the service creates an instance of the repository _listingRepository = new ListingRepository(); _listingRepository = New ListingRepository()

C#

VB

 Replacing one layer would require modifying the whole application • For example, replacing the repository with an nHibernate implementation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-30

Loose Coupling With Dependency Injection  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-31

Using Ninject  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

DLL = dynamic link library

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-32

The Dependency Resolver (C#) C#

public class NinjectConfig : IDependencyResolver { private readonly IKernel _kernel; Ninject kernel public NinjectConfig() { _kernel = new StandardKernel();

Binding interfaces to classes

_kernel.Bind().To(); _kernel.Bind().To(); } public object GetService(Type serviceType) { return _kernel.TryGet(serviceType); }

Called by the MVC infrastructure when a concrete type is required

public IEnumerable GetServices(Type serviceType) { return _kernel.GetAll(serviceType); } }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-33

The Dependency Resolver (VB) VB

Public Class NinjectConfig Implements IDependencyResolver Private ReadOnly _kernel As IKernel Ninject kernel Public Sub New() _kernel = New StandardKernel()

Binding interfaces to classes

_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 Called by the MVC Return _kernel.TryGet(serviceType) infrastructure when a End Function concrete type is required Public Function GetServices(serviceType As Type) _ As IEnumerable(Of Object) Implements IDependencyResolver.GetServices Return _kernel.GetAll(serviceType) End Function End Class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-34

Registering the Dependency Resolver  Typically done in global.asax • Application_Start method called when the application starts • Call static SetResolver method of the MVC DependencyResolver class DependencyResolver.SetResolver(new NinjectConfig()); DependencyResolver.SetResolver(New NinjectConfig())

C#

VB

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-35

Optional Hands-On Exercise 3.4

In your Exercise Manual, please refer to Optional Hands-On Exercise 3.4: Adding the Ninject DI Container

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-36

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-37

Chapter Review 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? Table Column Row Relation

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

3-38

Chapter 4

The Controller

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-2

Chapter Contents

 The Controller Class  Action Methods and ActionResult  Filters  Routing  Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-3

The Controller Is the Conductor  The controller receives requests from the client • Asks the model to do the processing • Selects the view to build the response

Request Response

Controller

Model

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-4

The Controller Class  Implements the IController interface • Custom controllers usually derive from the Controller class  The Controller class has many properties • Some of them are shown below Property

Description

HttpContext

HTTP-specific information about the HTTP request

Request

Contains data about the request

Response

Used to add data to the response

RouteData

Route data for the current request

Session

ASP.NET session object

TempData

Dictionary used to store data from one request to the next

 Controller-derived classes contain action methods • Called when requests are made from the browser

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-5

Storing Data on the Server  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 element • Session can also be closed by code with Session.Abandon()

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-6

Storing Data on the Server—Illustrated  Setting data in TempData or Session C#

TempData["name"] = "foo"; or Session["name"] = "foo";

VB

TempData("name") = "foo" or Session("name") = "foo"

 Getting data from TempData or Session var nameTemp = TempData["name"]; or var nameSession = Session["name"];

C#

VB

Dim nameTemp = TempData("name") or Dim nameSession = Session("name")

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-7

Chapter Contents

 The Controller Class

 Action Methods

and ActionResult

 Filters  Routing  Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-8

Action Methods  A controller can have several action methods • Each action method corresponds to a specific URL • Defined by the application’s routing rules

Routing is covered later in this chapter

http://localhost:1234/Listing/List

C#

public class ListingController : Controller { public ActionResult List() Public Class ListingController { Inherits System.Web.Mvc.Controller return View(); } Function List() As ActionResult } Return View() End Function End Class

VB

 An action method returns an ActionResult • Base class has just one method: ExecuteResult • ExecuteResult generates the output and puts it in the response

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-9

Action Method Parameters  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 http://localhost:1234/ListingItem/List?listingId=12 C#

public ActionResult List(int listingId) { return View(); Function List(listingId As Integer) As ActionResult } Return View() End Function

VB

 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 Forms and form data are covered later

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-10

Mapping Parameters to Complex Data  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 http://localhost:1234/Simple/Display2?Name=Fred&Age=12 C#

public string Display2(Person person) { public class Person } { public string Name { get; set; } public int? Age { get; set; } Person.Name is Fred } Person.Age is 12 Public Function Display2(person As Person) End Function

VB

Public Class Person Property Name As String Property Age As Integer? End Class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-11

Do Now 4a: Action Method Parameters

Do Now

1. 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-12

ActionResult  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-13

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 response

JsonResult

Json

Return some JSON data

EmptyResult

null

Does not return anything

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-14

Chapter Contents

 The Controller Class  Action Methods and ActionResult

 Filters  Routing  Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-15

Processing a Request in an MVC Application 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-16

From Request to Response

Request

Routing Controller Factory Controller Action Invoker

Response

Action Method

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-17

Attributes and MVC Filters  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-18

Built-In Filters  Main built-in filters Filter attribute

Description

Authorize

Authorize caller to execute action method

HandleError

Process unhandled exceptions

RequireHttps

Require/redirects to HTTPS to call action

ValidateInput ValidateAntiForgeryToken

Apply security to user input

ChildActionOnly

Action 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-19

Action and Result Filters  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 Controller 1

Before action filter After action filter

MVC framework 3

Action method 2

Before result filter After result filter

ActionResult 4

 Custom action filters can also be defined • Implementing the IActionFilter and/or IResultFilter interfaces • Or in a class that derives from ActionFilterAttribute

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-20

Custom Action Filter  ActionFilterAttribute implements both IActionFilter and IResultFilter interfaces • To use, define a class that derives from ActionFilterAttribute • Has four overridable methods Method

Description

OnActionExecuting

 Called before an action method is executed

OnActionExecuted

 Called after an action method is executed

OnResultExecuting

 Called before the ExecuteResult method is executed on an action result

OnResultExecuted

 Called after the ExecuteResult method is executed on an action result

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-21

Do Now 4b: Profiling With Action Filters

Do Now

1. 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 Index method • C# code: [ProfileFilter] • VB code: 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 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-22

OutputCache Attribute  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-23

OutputCache Attribute Properties  Main properties of the OutputCache attribute Property

Description

Duration

Time in seconds before the cache expires

VaryByParam

Semicolon-separated list of GET or POST values that will cause distinct copies to be cached; if *, all variations will be cached separately

Location

Location where the cache is stored; can be Server, Client, Downstream (client or proxies), ServerAndClient, Any, or None

CacheProfile

Use settings from the OutputCacheSettings in Web.config

SqlDependency

Use the ASP.NET/SQL Server cache dependency feature

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-24

Hands-On Exercise 4.1

In your Exercise Manual, please refer to Hands-On Exercise 4.1: Caching Action Method Output

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-25

Chapter Contents

 The Controller Class  Action Methods and ActionResult  Filters

 Routing  Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-26

Routing  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-27

Why Routing?  URLs are often directly mapped to the folder structure of the website http://www.server.com/admin/pages/index.html

• Could map to

C:\wwwroot\accounting\admin\pages\index.html

• URLs can also have parameters http://www.server.com/admin/pages/index.html?id=567h98gf-66&opt=password

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-28

URL Structure and Route Patterns  Routing rules apply to URL segments after the server name http://www.server.com/Home/Index

Protocol

Server

Segment 1

Segment 2

 A route table defines a URL pattern • Mapped to the slash-separated URL segments • Named segments are between curly braces http://www.server.com/ListingItem/ItemList/1 {controller}/{action}/{id}

• 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-29

Using Route Values  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 C#

RouteData.Values["action"]

RouteData.Values("action")

VB

• Custom route segments can also be received as parameters of action methods public ActionResult List(int id)

C#

Function List(id As Integer) _ As ActionResult

VB

Mapped from an integer route value named id

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-30

Registering Routes  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 C#

routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); Default controller is Home

Default action is Index

id parameter is optional VB

routes.MapRoute( name:="Default", url:="{controller}/{action}/{id}", defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} )

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-31

Adding a New Route  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 C#

routes.MapRoute("List", "List/{id}", new { controller = "ListingItem", action = "ItemList" }); routes.MapRoute("Default", // Default route omitted (see previous slide)

VB

routes.MapRoute("List", "List/{id}", New With {.controller = "ListingItem", .action = "ItemList"}) routes.MapRoute("Default", 'Default route omitted (see previous slide)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-32

Attribute Routing  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 routes.MapMvcAttributeRoutes();

C#

routes.MapMvcAttributeRoutes()

VB

• Add Route attributes on action methods and/or controller classes C#

[Route("List/{id}")] public ActionResult ItemList(int id)

Function ItemList(id As Integer) As ActionResult

VB

A URL like /List/2 will be mapped to the ItemList action method

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-33

Default Values  Default values can be defined for route segments • To define URL /List to be equivalent to /List/1: Route("List/{id=1}")

 Default values can also apply to action methods • To define Index as the default action method, apply attribute to controller: Route("{action=Index}")

 A parameter can be made optional with a ? suffix • The following route will be processed for /List/Food or /List Route("List/{name?}")

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-34

Route Constraints  Route constraints restrict a route to specific data types or values • Apply constraint to route segment Route("List/{id:int}")

• 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 Route("List/{id:int:min(0):max(10)}"

• This route will only apply if the id segment of the URL is an integer between 0 and 10

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-35

Factorizing Route Segments  In a controller, many action methods can use a common segment • Usually the controller name C#

[Route("Home/Index")] public ActionResult Index()

VB

Function Index() As ActionResult

• Can be set once with a RoutePrefix attribute on the controller [RoutePrefix("Home")] public class HomeController : Controller { [Route("Index")] public ActionResult Index()

Public Class HomeController Inherits System.Web.Mvc.Controller

C#

VB

Function Index() As ActionResult

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-36

Factorizing Route Segments

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-37

Hands-On Exercise 4.2

In your Exercise Manual, please refer to Hands-On Exercise 4.2: Customizing Routes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-38

Bypassing the Route System  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 routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

• 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-39

Outgoing Routing  Outgoing routing builds URLs using the route table • The ActionLink HTML helper uses the route table • Output with the default route: @Html.ActionLink("About", "About", new { id = 15 }) About

 RouteLink is similar • But can also create a link for other resources, such as files • This link is the same as the previous one: @Html.RouteLink("About", new { action = "About", id = 15 })

 The Url helper class helps create a URL following the route table var url = Url.RouteUrl(new { action = "About", id = 15 }); Dim myUrl = Url.RouteUrl(New With {.action = "About", .id = 15})

C# VB

URL contains /Home/About/15

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-40

Outgoing Routing with Attribute Routing  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 [Route("~/Show", Name="ShowRoute")]



• Can be used with @Html.RouteLink("Display", "ShowRoute")

• Or Display

Code at C:\977\xx\Demo\Chapter 4\Outgoing AttributeRouting

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-41

Chapter Contents

 The Controller Class  Action Methods and ActionResult  Filters  Routing

 Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-42

The Need for Areas  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Admin area

Blog area

4-43

Routing and Areas  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 AreaRegistration.RegisterAllAreas();

 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 [RouteArea("Admin")] [RoutePrefix("Users")] [Route("{action}")] public class UsersController : Controller

C#

Public Class UsersController Inherits Controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-44

VB

Outgoing Links to Areas  ActionLink can generate links to areas • Add an area property to the RouteValues parameter @(Html.ActionLink("Administration", "Index", new { area = "Admin", controller = "Users" }))

C#

@Html.ActionLink("Administration", "Index", New With {.area = "Admin", .controller = "Users"})

VB

 Views in an area have their own layout page • Can reuse the main layout view with a _ViewStart.xxhtml in the area

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-45

Hands-On Exercise 4.3

In your Exercise Manual, please refer to Hands-On Exercise 4.3: Structuring an Application With Areas

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-46

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-47

Chapter Review 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?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4-48

Chapter 5

Forms and User Input

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-2

Chapter Contents

 HTML Forms and MVC  Simplifying HTML Generation With Helpers  Developing Custom HTML Helpers  Display and Editor Helper Methods  Validating Data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-3

Getting Input From Users  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-4

HTML Forms  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 Action method called when form is submitted

Name must be supplied

Title:

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-5

Supplying Default Values  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 C#

var model = new ListingItem { Title = "Meeting", Notes = "At 5pm" }; return View(model); Dim model = New ListingItemModel With {.Title = "Meeting", .Notes = "At 5pm"} Return View(model) Default values

Title: @Model.Notes

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-6

VB

Form Data  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 With the post method, data is put in the request body Title: Notes:

title=Meeting¬es=With+Stacy%0D%0Aat+5pm

Data is encoded

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-7

Processing Form Data in an Action Method  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 Title: Notes:

[HttpPost] public ActionResult Index(string title, string notes) { }

C#

VB

Public Function Index(title As String, notes As String) As ActionResult End Function

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-8

One Form, Two Action Methods  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 VB

public ActionResult Index() { var model = ...; return View(model); }

Public Function Index() As ActionResult Dim model = ... Return View(model) End Function Public Function Index(model As ListingItemModel) _ As ActionResult Return View("Confirm", model) End Function

[HttpPost] public ActionResult Index(ListingItemModel model) { return View("Confirm", model); }

Navigate to other view, once processing is done C#

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-9

One Form, Two Action Methods—Illustrated Browser User clicks a link or button to request the form

Controller GET initial request Form

Form User submits the form

Get action method

POST request Next page

Post action method

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-10

Experimenting With an HTML Form

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-11

Do Now 5a: Editing Items in an HTML Form

Do Now

1. Open the Do Now 5a starting point in C:\977\xx\Do Nows\Do Now 5AStarting 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-12

Chapter Contents

 HTML Forms and MVC

 Simplifying HTML Generation With Helpers  Developing Custom HTML Helpers  Display and Editor Helper Methods  Validating Data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-13

HTML Helpers  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 @using (Html.BeginForm()) { Title: m.Title)

C#

C#

Property Title As String

@Html.LabelFor(Function(m) m.Title)

Please enter title:

for associates the label with the textbox

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-19

VB

VB

HTML List Boxes and Drop-Down Lists  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 @foreach (var item in Model) { @item.Title (@item.Notes) } @For Each item In Model @@item.Title (@item.Notes) Next

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

C#

VB

5-20

List Helpers  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 @Html.DropDownList("list", new SelectList(Model, "Id", "Title", 2))

List name

Ienumerable List to display

Value property

Text property

@Html.DropDownList("list", new SelectList(Model, "Id", "Title", 2))

C#

Default value VB

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-21

DropDownListFor With a SelectList in a Model (C#) C#: Model

public class ListingModel { public SelectList List { get; set; } public int SelectedId { get; set; } }

List Selected item C#: View

@using (Html.BeginForm()) { @Html.DropDownListFor(m => m.SelectedId, Model.List) }

C#: Controller

public ActionResult ListWithModel() { var model = new ListingModel { List = new SelectList(_list, "Id", "Title") , SelectedId = 2 }; return View(model); } [HttpPost] public ActionResult ListWithModel(ListingModel model) { ... }

model.SelectedId has the selected value

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-22

DropDownListFor With a SelectList in a Model (VB) VB: Model

Public Class ListingModel Public Property List As SelectList Public Property SelectedId As Integer End Class

List Selected item VB: View

@Using Html.BeginForm() @Html.DropDownListFor(Function(m) m.SelectedId, Model.List) @ End Using

VB: Controller

Public Function ListWithModel() As ActionResult Dim model = New ListingModel() With _ { .List = New SelectList(_list, "Id", "Title"), .SelectedId = 2 } Return View(model) End Function model.SelectedId has the selected value _ Public Function ListWithModel(model As ListingModel) As ActionResult ... End Function

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-23

Using List HTML Helpers

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-24

Uploading Files  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 @(using (Html.BeginForm("AddPhoto", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))) { }

C#

 Action method receives the file as a parameter • Type is HttpPostedFileBase • Also available through the Request.Files property [HttpPost] public ActionResult AddPhoto(HttpPostedFileBase file) { }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

C#

5-25

Processing Uploaded Files  HttpPostedFileBase properties and methods Property or method

Description

ContentLength

Size of file in bytes

ContentType

MIME type of file

FileName

Full name of file on the client

InputStream

Stream that points to the file content

SaveAs

Method to save the file on the server

 Server object in controller has a MapPath method • Returns the physical path on the server for a logical path Server.MapPath("~/Photos");

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-26

Uploading Photos

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-27

Hands-On Exercise 5.1

In your Exercise Manual, please refer to Hands-On Exercise 5.1: Replacing HTML Elements With HTML Helpers

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-28

Chapter Contents

 HTML Forms and MVC  Simplifying HTML Generation With Helpers

 Developing Custom HTML Helpers  Display and Editor Helper Methods  Validating Data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-29

Extension Methods  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-30

An HTML Helper Extension Method  Method that builds a link made of text and image • The standard ActionLink method generates an element with text • The ImageActionLink custom helper will generate an 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 HtmlHelper instance

@Html.ImageActionLink(...)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-31

An HTML Helper Extension Method Class and method must be static C#

public static class MyExtensions { public static HtmlString ImageActionLink(this HtmlHelper html, ... { First parameter decorated with this

} } Method must be in module

Extension attribute for extension method

VB

Public Module MyExtensions Public Function ImageActionLink(html As HtmlHelper, ...) As HtmlString End Function End Module

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-32

The TagBuilder Class  Simple class to help building HTML elements • Constructor takes the name of the element C#

var link = new TagBuilder("a"); Dim link = New TagBuilder("a")

VB

• Methods and properties to customize the element Method/Property

Description

AddCssClass

Add values to the class attribute

MergeAttribute

Add an attribute to the element

SetInnerText

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-33

The UrlHelper Class  Builds URLs from route values • Can be accessed through the Url property in views • Constructor takes a request context C#

var urlHelper = new UrlHelper(html.ViewContext.RequestContext); Extending the HtmlHelper class gives access to its members Dim urlHelper = New UrlHelper(html.ViewContext.RequestContext)

VB

• Methods return URLs Method

Description

Action

Several overloads to generate a URL from action, controller, route values

RouteUrl

Generate a URL from a route name

Content

Convert a virtual path to an absolute path

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-34

Building an Anchor Link Parameters passed to the extension method

var link = new TagBuilder("a"); link.Attributes.Add("href", urlHelper.Action(actionName, controllerName, routeValues)); link.SetInnerText(linkText); // Use with: link.ToString() @Html.MyActionLink(listing.Title, "List", "ListingItem", new { id = listing.Id })

C#

View: C#

Food Dim link = New TagBuilder("a") link.Attributes.Add("href", urlHelper.Action(actionName, controllerName, routeValues)) link.SetInnerText(linkText) ' Use with: link.ToString() @Html.MyActionLink(listing.Title, "List", "ListingItem", New With {.id = listing.Id})

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

View: VB

5-35

Do Now 5b: Using a Custom HTML Helper

Do Now

1. Open the Do Now 5b starting point in C:\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 Web project 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-36

Helper Classes  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-37

Hands-On Exercise 5.2

In your Exercise Manual, please refer to Hands-On Exercise 5.2: Developing a LabelTextBox HTML Helper

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-38

Chapter Contents

 HTML Forms and MVC  Simplifying HTML Generation With Helpers  Developing Custom HTML Helpers

 Display and Editor Helper Methods  Validating Data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-39

Model-Driven User Interface  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-40

Editing and Displaying the Whole Model  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 Attribute

Description

ScaffoldColumn

If constructor is passed false, no HTML is rendered for property

HiddenInput

Generates an input type="hidden" element for Editor methods; no HTML rendered with Display methods if DisplayValue is false

DisplayFormat

Controls the formatting of the output; NullDisplayText is the text displayed if value is null; DataFormatString is a formatting string

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-41

Using Editor and Display Attributes [HiddenInput(DisplayValue = false)] public int Id { get; set; }

C#

[DisplayFormat(NullDisplayText = "-", DataFormatString="{0:D}")] [Display(Name = "Due Date")] public DateTime? DueDate { get; set; } [ScaffoldColumn(false)] public int? LookAndFeelId { get; set; } @Html.DisplayForModel() Property Id As Integer

VB

Property DueDate As DateTime? Property LookAndFeelId As Integer?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-42

Editor and EditorFor  EditorFor replaces more specific HTML input methods • The generated HTML is driven by data type • Can be customized with attributes @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#

VB

@Html.TextBoxFor(Function(m) m.Title) @Html.CheckBoxFor(function(m) m.Done) @Html.TextBoxFor(function(m) m.Notes) VB

@Html.EditorFor(Function(m) m.Title) @Html.EditorFor(function(m) m.Done) @Html.EditorFor(function(m) m.Notes)

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-43

Customizing the Generated HTML  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 [DataType(DataType.EmailAddress)]

C#



VB

– and [EmailAddress]

C#

VB



© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-44

DataType Attribute  Main DataType enumeration values DataType value

Description

MultilineText

Generates a textarea HTML element

Password

Generates an input of type password

Date, Time

Display the date or time part of a DateTime property

EmailAddress

Generates a mailto: anchor element

Url

Generates an anchor element

 Other values will generate validation code • CreditCard, PhoneNumber, PostalCode… • Validate the format, not the value Validation is covered in next section

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-45

Custom Display and Editor Templates  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-46

Hands-On Exercise 5.3

In your Exercise Manual, please refer to Hands-On Exercise 5.3: Using Edit and Display Templates

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-47

Chapter Contents

 HTML Forms and MVC  Simplifying HTML Generation With Helpers  Developing Custom HTML Helpers  Display and Editor Helper Methods

 Validating Data

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-48

Client and Server Validation  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-49

Validation During Model Binding  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: Ten today ListingId=1&Title=Cookies&Done=false&Notes=&Quantity=Ten&Priority=Normal&DueDate=today

• Model – in action method parameter:

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-50

ModelState  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-51

Validating the Model in an Action Method  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 C#

[HttpPost] public ActionResult ItemEdit(ListingItemModel model) { if (!ModelState.IsValid) return View(model); If errors found, return view

No error found _listingItemService.Update(model); return RedirectToAction(“ItemList", new { id = model.ListingId }); } VB

Public Function ItemEdit(model As ListingItemModel) As ActionResult If Not ModelState.IsValid Then If errors found, return view Return View(model) End If No error found _listingItemService.Update(model) Return RedirectToAction(“ItemList", New With {.id = model.ListingId}) End Function

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-52

Adding Custom Validation  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 C#

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

VB

If ModelState.IsValidField("Quantity") AndAlso model.Quantity.HasValue AndAlso model.Quantity < 0 Then ModelState.AddModelError("Quantity", "Quantity must not be negative") End If

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-53

Displaying Error Messages  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 @Html.ValidationSummary("Errors found:")

C#

Text passed to AddModelError

@Html.LabelFor(m => m.Quantity) @Html.EditorFor(m => m.Quantity) @Html.ValidationMessageFor(m => m.Quantity) (remaining lines omitted)

@Html.ValidationSummary("Errors found:")

VB

@Html.LabelFor(Function(m) m.Title) @Html.EditorFor(Function(m) m.Title) @Html.ValidationMessageFor(Function(m) m.Title) (remaining lines omitted)

Default text supplied by MVC input-validation-error class defined in Site.css

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-54

Controlling Validation With Attributes  Many validation rules are encapsulated in attributes • Defined in System.ComponentModel.DataAnnotations namespace • All attributes have an ErrorMessage property to specify the error message Attribute

Description

Required

Field must not be blank

StringLength

Specify maximum and minimum length

Compare

Value should be equal to another property

Range

Value between two numbers or other types

CreditCard

Valid credit card number format

EmailAddress

Valid e-mail address format

Phone

Valid phone number format

RegularExpression

Validate field with regular expression

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-55

Defining a Custom Validation Attribute  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 public class FutureDateValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { var date = value as DateTime?; return date == null || date > DateTime.Today; } } Public Class FutureDateValidationAttribute Inherits ValidationAttribute

C#

VB

Public Overrides Function IsValid(value As Object) As Boolean Dim dt = CType(value, DateTime?) Return dt Is Nothing OrElse dt > DateTime.Today End Function End Class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-56

Validating on the Client  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

More on bundles in next chapter

@Scripts.Render("~/bundles/jqueryval")

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-57

Hands-On Exercise 5.4

In your Exercise Manual, please refer to Hands-On Exercise 5.4: Adding Validation to the Case Study

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-58

Scaffolding With Visual Studio  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

Template to use Model class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-59

Do Now 5c: Experimenting With Scaffolding

Do Now

1. Open the Do Now 5c starting point in C:\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 ItemDisplay with 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-60

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-61

Chapter Review 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

5-62

Chapter 6

Client-Side Features

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-2

Chapter Contents

 Introduction to jQuery  Ajax  Adapting to Mobile Devices  International Applications  WebGrid and Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-3

Server-Side and Client-Side Technologies  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 Client

Server

Browser

Controller

Model

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-4

JavaScript and jQuery  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-5

Introducing jQuery  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 () { … }); Your jQuery code goes here

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-6

jQuery Selectors  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 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

®

To learn more on jQuery: Course 1610, jQuery Introduction

1610

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-7

Using jQuery  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

script section defined in layout Will be called when DOM is loaded

Adds click @section scripts { event handler $(function () { $('#button').click(function () { alert('Thanks!'); }); Parameter is a function, }); called when event is raised }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-8

jQuery in Action

Demo

 Your instructor will demonstrate a page with jQuery code • Start application • Select jQuery or Animation • Click a color Red Green Blue $(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

C:\977\xx\Demo\Chapter 6\jQuery

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-9

Bundling and Minification  Web pages often need several JavaScript and CSS files • Each is included with a or 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-10

Bundling Configuration  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.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js"));

C#

Files to include

 Bundles are referenced from pages • Typically in the layout page • Identified by the bundle name

Bundle name

@Scripts.Render("~/bundles/jquery")

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-11

Demo: Observing the Effect of Bundling

Demo

1. 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 and press 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?

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-12

Demo: Observing the Effect of Bundling

Demo

8. Close Internet Explorer and change Layout definition in _ViewStart to Layout = "~/Views/Shared/_LayoutWithBundling.cshtml"

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 and press 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-13

jQuery UI  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-14

Do Now 6a: Adding a jQuery UI Datepicker

Do Now

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 followed by

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-15

Chapter Contents

 Introduction to jQuery

 Ajax  Adapting to Mobile Devices  International Applications  WebGrid and Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-16

Ajax  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 Client

Server GET or POST

jQuery code

3 4

1

Ajax request

Action method Action method

2

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-17

Ajax and Action Methods  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-18

JSON  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 JSON

{ "Id": 5, "Name": "Pink", "FontName": "Times New Roman", "FontSize": 12, "ForeColor": "Pink", "BackColor": "LightGreen" }

 Very similar to JavaScript object literals • Declare arrays with square brackets jQuery

var person = { Name: "Fred", Scores: [ 10, 12, 8 ] };

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-19

MVC and JSON  Action methods can return JSON data • With the JsonResult class that derives from ActionResult • Or the Json helper method var item = _lookAndFeelService.Read(id); return Json(item, JsonRequestBehavior.AllowGet);

Pass any object

C#

Necessary if action method is GET

Dim item = _lookAndFeelService.Read(id) Return Json(item, JsonRequestBehavior.AllowGet)

VB

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-20

jQuery Ajax Methods  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 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

• Using the $.get shortcut Action method to call Optional parameters Function called when response is received

jQuery

$.get( '/ListingItem/EditLookAndFeel', { id: $('#LookAndFeelId').val() }, function (data) { } );

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-21

Displaying a Pop-Up Modal Dialog With Ajax and jQueryUI  Define a partial view and an action method that returns it • Partial view named EditLookAndFeel Please select the Look and Feel: @Html.DropDownList("LookAndFeelList")

• Action method

C#

public ActionResult EditLookAndFeel(int id) { var list = _lookAndFeelService.List(); ViewBag.LookAndFeelList = new SelectList(list, "Id", "Name", id); return PartialView(); } VB

Public Function EditLookAndFeel(id As Integer) As ActionResult Dim list = _lookAndFeelService.List() ViewBag.LookAndFeelList = New SelectList(list, "Id", "Name", id) Return PartialView() End Function

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-22

Displaying a Pop-Up Modal Dialog With Ajax and jQueryUI  Call the action method and process the returned data from jQuery code data contains the HTML from partial view jQuery

$.get('/ListingItem/EditLookAndFeel', { id: $('#LookAndFeelId').val() }, Place the data function (data) { inside the div $('#divLookAndFeel').html(data).dialog({ modal: true, width: 500, dialog is defined buttons: { /* code omitted */ } by jQueryUI } }); Options defined with }); an object

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-23

Hands-On Exercise 6.1

In your Exercise Manual, please refer to Hands-On Exercise 6.1: Using jQuery and Ajax to Display a Dialog Box

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-24

Chapter Contents

 Introduction to jQuery  Ajax

 Adapting to Mobile Devices  International Applications  WebGrid and Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-25

Mobile Applications  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

Learning Tree has a site adapted to mobile devices. The desktop version has been requested here for demonstration purposes! iOS = iPhone OS OS = operating system

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-26

Adapting Applications for Mobile Devices  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 Applies only to screens less that 850 px wide

@media only screen and (max-width: 850px) { } Any rule defined here overrides previous rules

 Bootstrap is included with Visual Studio and defines many CSS rules • Used in the ListPlus application

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-27

The Mobile Viewports  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 width Display viewport width

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-28

Testing Mobile Applications  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-29

Mobile Views  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 if (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice) { // Request originates from 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-30

Adding a New Display Mode Condition  In the Application_Start method of Global.asax • List.iPhone.xxhtml will be used if condition is true Insert in first position DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone") { ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) }); Insert in first position

Condition

C#

Part of file name VB

DisplayModeProvider.Instance.Modes.Insert(0, New DefaultDisplayMode("iPhone") With { Condition .ContextCondition = (Function(context) context.GetOverriddenUserAgent(). IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) })

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-31

Hands-On Exercise 6.2

In your Exercise Manual, please refer to Hands-On Exercise 6.2: Adapting ListPlus to Mobile Devices

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-32

jQuery Mobile  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

Same view on desktop and mobile device

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-33

jQuery Mobile and HTML5  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 tag with a value of listview

 To change a link into a buttonlike link • Add a data-role attribute to the tag with the value button Edit

Without button role With button role

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-34

Optional Demo: jQuery Mobile

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-35

Chapter Contents

 Introduction to jQuery  Ajax  Adapting to Mobile Devices

 International Applications  WebGrid and Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-36

Globalizing Applications  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-37

Culture Basics  .NET defines the CultureInfo class for globalization • In the System.Globalization namespace • Culture can be defined by its name, region-dependent (neutral) or not Culture name

Description

en

English (region-independent)

en-US

U.S. English

en-UK

U.K. English

fr-FR

France French

• 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-38

Resources  .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 C#

var msg = Resources.Models.ListingItemModel.PriorityQuantityError; VB

Dim msg = Resources.My.Resources.ListingItemModel.PriorityQuantityError

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-39

Optional Hands-On Exercise 6.3

In your Exercise Manual, please refer to Optional Hands-On Exercise 6.3: Making the ListPlus Application International

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-40

Chapter Contents

 Introduction to jQuery  Ajax  Adapting to Mobile Devices  International Applications

 WebGrid and Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-41

Grid and Chart Tools  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 …

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-42

Creating a WebGrid  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 C#

@{ var grid = new WebGrid(Model, canPage: false); } @code Dim grid = New WebGrid(Model, canPage:=False) End Code

VB

 The grid is rendered with the GetHtml method • Returns the grid HTML • Has many optional parameters @grid.GetHtml()

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-43

Customizing a WebGrid  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 @(grid.GetHtml(columns: { new WebGridColumn { new WebGridColumn { new WebGridColumn { }))

new List

C#

ColumnName = "Title", CanSort = true }, ColumnName = "Quantity" }, ColumnName = "Done" }

@(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"} }))

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

VB

6-44

Generating Charts in Controllers  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 var chart = new Chart(600, 600); chart.AddSeries("Quantity", xValue: titles, yValues: quantities); Collection for x-axis values

C#

Collection for y-axis values

Dim chrt = New Chart(600, 600) chrt.AddSeries("Quantity", xValue:=titles, yValues:=quantities)

VB

 Chart creates an in-memory image • Returned to the client as an image with File helper return File(chart.GetBytes(), "image/jpeg"); Return File(chrt.GetBytes(), "image/jpeg")

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

C# VB

6-45

Rendering a Chart on a Page  To render a chart on a page, simply use the HTML element • Set the src attribute to the action method • Passing it the necessary parameters

C#

VB

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-46

Hands-On Exercise 6.4

In your Exercise Manual, please refer to Hands-On Exercise 6.4: Displaying Data in a Grid and a Chart

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-47

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-48

Chapter Review 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

6-49

Chapter 7

Building Professional Applications

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-2

Chapter Contents

 Controlling User Access  Error Handling and Debugging  Unit Testing  Web API and Distributed Applications

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-3

Authentication and Authorization  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-4

The Authorize Attribute  The Authorize attribute is a filter • Can be applied to a single method [Authorize] public ActionResult Index()

C#

Public Function Index() As ActionResult

• Or to a controller [Authorize] public class AdminController : Controller Public Class AdminController Inherits System.Web.Mvc.Controller

C#

VB

• Or added as a global filter in the FilterConfig class in App_Start filters.Add(new AuthorizeAttribute());

C#

VB

filters.Add(New AuthorizeAttribute())

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-5

VB

Authorize and AllowAnonymous Attribute  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 [Authorize(Roles="Admin,SuperAdmin")]

C#

VB



 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! [AllowAnonymous] public class AccountController : Controller

C#

VB

Public Class AccountController Inherits System.Web.Mvc.Controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-6

ASP.NET Identity  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-7

Individual User Accounts  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-8

The Authorization Cookie  Initial request has no authorization cookie • After login, requests and responses have an authorization cookie Request action marked Authorize

Yes

Authorization cookie in request?

No

Call Login action Login view

Put authorization cookie in response

Yes

Login successful?

No

Redirect to requested action Call requested action

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-9

OAuth and OpenID  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 OAuthWebSecurity.RegisterFacebookClient( appId: "xxxxxxxxxxxxxx", appSecret: "yyyyyyyyyyyyy");

C#

OAuthWebSecurity.RegisterFacebookClient( appId:="xxxxxxxxxxxxxx", appSecret:="yyyyyyyyyyyyy")

VB

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-10

Individual Account Authentication

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-11

Hands-On Exercise 7.1

In your Exercise Manual, please refer to Hands-On Exercise 7.1: Adding Authentication and Authorization

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-12

Other Authentication Options  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-13

More Security Options  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

SSL = Secure Sockets Layer

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-14

Chapter Contents

 Controlling User Access

 Error Handling and Debugging  Unit Testing  Web API and Distributed Applications

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-15

Handling Exceptions With the HandleError Attribute  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-16

Using Custom Errors  Global filters are defined in FilterConfig class, in App_Start folder • RegisterGlobalFilters is called from global.asax • Other filters can be registered there filters.Add(new HandleErrorAttribute())

 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 Set the value in the Web.config file located at the root of the website, not in the Views folder

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-17

HandleErrorInfo Class  The HandleErrorInfo class is passed as the model to the error view • ActionName and ControllerName properties • Exception property gives access to the exception details Exception @Model.Exception.Message
In action method @Model.ActionName of @Model.ControllerName controller

 The code in the error handling view must be tested carefully • If an exception occurs, the default yellow page will be displayed

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-18

Do Now 7a: The HandleErrorAttribute

Do Now

1. Open and build the Do Now 7a starting point in C:\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 • A yellow page is displayed 4. Open the Web.config file located at the application root; add the following line below the 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 @Html.Raw(Model.Exception.StackTrace.Replace("\n", "
"))

8. Run the application using and notice the custom error page

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-19

Chapter Contents

 Controlling User Access  Error Handling and Debugging

 Unit Testing  Web API and Distributed Applications

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-20

Unit Testing and Test-Driven Development  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

®

Course 511, .NET Best Practices and Design Patterns

511

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-21

Unit Testing MVC Applications  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 Visual Studio Tests or NUnit

Tests

Controller

View

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-22

Running Tests  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 Attribute

Description

TestClass

Class is included in tests

TestMethod

Method is called during tests

ClassInitialize

Method called when class is loaded

ClassCleanup

Method called when class is unloaded

TestInitialize

Method called before each test in class

TestCleanup

Method called after each test in class

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-23

Test Methods (C#)  A test method has three phases • Arrange: Instantiate the controller and other resources • Act: Call the method being tested • Assert: Test the result values [TestClass] public class HomeControllerTest { [TestMethod] public void Index() { // Arrange var controller = new HomeController();

C#

// Act var result = controller.Index() as ViewResult; // Assert Assert.AreEqual(result.ViewName, "Index");

Cast result to give access to ViewName property

} }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-24

Test Methods (VB)

VB

Public Class HomeControllerTest Public Sub Index() Dim controller = New HomeController() Dim result = DirectCast(controller.Index(), ViewResult) Assert.AreEqual("Index", result.ViewName) End Sub End Class

Cast result to give access to ViewName property

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-25

Assert  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 Method

Description

AreEqual/AreNotEqual

Values are equal/are not equal

AreSame/AreNotSame

Two variables reference the same object/different objects

IsTrue/IsFalse

Condition is true/false

IsInstanceOfType/ IsNotInstanceOfType

Object is/is not an instance of type

IsNull/IsNotNull

Object is/is not null

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-26

Tests and Visual Studio  Tests are done from within Visual Studio

Red light

Green light

Test result details

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-27

Do Now 7b: Adding Unit Testing to ListPlus

Do Now

1. Open and build the Do Now 7b starting point in C:\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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-28

Testing Complex Applications  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-29

Testing With Moq

Demo

 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-30

Chapter Contents

 Controlling User Access  Error Handling and Debugging  Unit Testing

 Web API and Distributed Applications

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-31

Distributed Applications  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 ®

2601 SOAP = Simple Object Access Protocol WSDL = Web Services Description Language

For more about WCF and web API, see Course 2601, WCF, Web API, and SignalR Services for .NET

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-32

Web API  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-33

Creating a New Web API Controller  In Add controller dialog, select Empty API controller • Other templates create controller with existing action methods  Add methods that map to HTTP verbs public class EmployeeController : ApiController { public List GetList() { return _employees; }

Return data to client

Maps to HTTP GET

C#

Base class is ApiController

Public Class EmployeeController Inherits ApiController

VB

Public Function GetList() As List(Of EmployeeModel) Return _employees End Function

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-34

Web API Route Table  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 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

Default prefix for URLs

C#

http://localhost:6666/api/Employee/2

config.Routes.MapHttpRoute( _ name:="DefaultApi", _ routeTemplate:="api/{controller}/{id}", _ defaults:=New With {.id = RouteParameter.Optional} )

VB

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-35

Web API Clients  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-36

Web API Server and Web Ajax Client

Demo

 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 and click the List Employees button • Use Fiddler to view and/or make requests

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-37

Hands-On Exercise 7.2

In your Exercise Manual, please refer to Hands-On Exercise 7.2: Building a Web API Controller

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-38

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-39

Chapter Review 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

7-40

Chapter 8

Application Deployment

Chapter Objectives 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-2

Chapter Contents

 Preparing and Deploying to IIS  Deploying to Windows Azure

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-3

Preparing Deployment  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-4

Modifying Web.config  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-5

Publishing the Application  Use BUILD | Publish on the web project • Can define several profiles • Each profile sets destination Publish method

Description

Web Deploy

Publish directly in IIS—Must have administrative rights

Web Deploy Package

Create package that can be imported in IIS

FTP

Publish to FTP folder

File System

Publish to local directory or network share

FPSE

FrontPage Server Extensions (legacy)

 Web Deploy includes instructions to configure IIS • Databases can also be included in the deployment package

FTP = File Transfer Protocol

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-6

IIS and ASP.NET MVC Applications  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-7

Hands-On Exercise 8.1

In your Exercise Manual, please refer to Hands-On Exercise 8.1: Deploying the Application

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-8

Chapter Contents

 Preparing and Deploying to IIS

 Deploying to Windows Azure

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-9

Windows Azure  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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-10

Creating a Windows Azure Website  On manage.windowsazure.com • Must have an account

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-11

Getting the Publish Profile  Download the publish profile and save to a file

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-12

Publishing to the Azure Website  Import profile into Visual Studio Publish wizard

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-13

Setting Connection Data  Connection data is automatically set

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-14

Modifying the Connection Strings  The wizard modifies the connection strings as appropriate • To use a SQL Database in Azure • Database must be deployed in Azure

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-15

Running in Azure  Application now runs in Azure!

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-16

Chapter Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

8-17

Chapter 9

Course Summary

Course Summary 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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

9-2

Appendix A

Answers to Review Questions

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-2

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-3

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

Class

Column

Property

Row

Object

Relation

Collection

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-4

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-5

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; }

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-6

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-7

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

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A-8

Suggest Documents