266
October 2015 MVC 4

MVC 4

Embed Size (px)

Citation preview

Page 1: MVC 4

October 2015

MVC 4

Page 2: MVC 4

MVC separates the user interface of an application into three main aspects:The ModelThe ViewThe Controler

Cont.

Page 3: MVC 4

A set of classes that describes the data you’re working with as well as the business rules for how the data can be changed and manipulated

The Model

Page 4: MVC 4

Defines how the application’s UI will be displayed

The View

Page 5: MVC 4

A set of classes that handles communication from the user, overall application flow, and application-specific logic.

The Controller

Page 6: MVC 4

Models:Represent domain objects that encapsulate:

data stored in a databasecode to manipulate the datacode to enforce domain-specific business logicExample: encapsulating Entity Framework

MVC as Applied to Web Frameworks

Page 7: MVC 4

View:Template to dynamically generate HTML

Controller:Class that manages the relationship between

the View and the ModelIt responds to user input, talks to the model,

and decides which view to render (if any).

Cont.

Page 8: MVC 4
Page 9: MVC 4

MVC is a pattern that can be applied to different frameworks

ASP.NET MVCThe MVC pattern has been applied to ASP.NET.

This does not mean that it is the same as MVC running in other places.

A Pattern

Page 10: MVC 4

10 months after MVC 2The Razor view engineSupport for .NET 4 Data AnnotationsImproved model validationGreater control and flexibility with support for

dependency resolution and global action filtersBetter JavaScript support with unobtrusive

JavaScript, jQuery Validation, and JSON binding

Use of NuGet to deliver software and manage dependencies throughout the platform

ASP.NET MVC 3

Page 11: MVC 4

Code-focused templating for HTML generation

Compact, expressive, and fluidNot a new languageEasy to learnWorks with any text editorIntelliSenseNo XML-like heavy syntax

Razor View Engine

Page 12: MVC 4
Page 13: MVC 4
Page 14: MVC 4

Features include:ASP.NET Web APIEnhancements to the default project templatesMobile project template using jQuery MobileDisplay ModesTask Support for Asynchronous ControllersBundling and Minification

ASP.NET MVC 4

Page 15: MVC 4

Referred to as Web APIA framework that offers the ASP.NET MVC

development style but is tailored to writing HTTP services. (service-oriented design)

Several MVC features have been adopted for HTTP Service domain:RoutingModel Binding and ValidationFiltersScaffoldingEasy Unit Testability

ASP.NET Web API

Page 16: MVC 4

Web API also adds a few new concepts and features to the HTTP service development:HTTP programming modelAction dispatching based on HTTP verbsContent negotiationCode-based configuration

Cont.

Page 17: MVC 4

http://www.asp.net/mvc/mvc5

ASP.NET MVC 5

Page 18: MVC 4

Enhancements to the default project templates

Page 19: MVC 4

Cont.

Page 20: MVC 4

A convention-based approach to allow selecting different views based on the browser making the request.

Index.cshtml vs Index.Mobile.cshtmlYou can also register your own custom

criteria.Index.WinPhone.cshtml

Display Modes

Page 21: MVC 4

Same as ASP.NET 4.5 Works on scripts and CSSMinifies the request via several techniquesCompresses the size of CSS via several

techniquesYou can create custom bundles to contain

specific scripts and reference them with a single URL

Bundling and Minification

Page 22: MVC 4

Cont.

Page 23: MVC 4

Json.NETIncluded in MVC 4 as a part of the Web API to

support serializing data to JSON format allowing for:Data contractsAnonoymous typesDynamic typesDatesTimeSpansObject reference presevationIndentingCamel casingLINQ to JSON is also included along with automatic

conversion from JSON to XML

Included Open Source Libraries

Page 24: MVC 4

DotNetOpenAuth:Used to support OpenID and Oauth-based

loginsFacebookMicrosoftGoogleTwitter

MVC 4 also provides an OAuthWebSecurity class

Cont.

Page 25: MVC 4

App_Start

Page 26: MVC 4

AuthConfig.csUsed to configure security settings, including sites

for OAuth login.BundleConfig.cs

Used to register bundles used by the bundling and minification system. By default it inlcudes jQuery, jQueryUI, jQuery valiation, Modernizr, and default CSS references

FilterConfig.cs:Used to register global MVC filters. By default the

HandlerErrorAttribute is registered. You can put other filter registrations here.

Cont.

Page 27: MVC 4

Filters:An action filter is an attribute that you can apply

to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:OutputCache – This action filter caches the output of

a controller action for a specified amount of time.HandleError – This action filter handles errors

raised when a controller action executes.Authorize – This action filter enables you to restrict

access to a particular user or role.

Cont.

Page 28: MVC 4

RouteConfig.csContains routing

WebApiConfig.csUsed to register Web API routes, as well as set

any additional Web API configuration settings

Cont.

Page 29: MVC 4

May 2012 the ASP.NET Web Stack open source announcement marked the transition of ASP.NET MVC, ASP.NET Web Pages, and ASP.NET Web API from open source licensed code to fully open source projects.

All code changes and issue tracking for these projects is done in public code repositories, and these projects are allowed to accept community code contributions if the team agrees that the changes make sense.

http://aspnetwebstack.codeplex.com/SourceControl/list/changesets

Open Source Release

Page 30: MVC 4

Visual Studio 2012 (included)Can be installed on:

Visual Studio 2010 SP1Visual Web Developer 2010 Express SP1

Can be installed side-by-side previous versions of MVC

Installing MVC 4

Page 31: MVC 4

Templates

Page 32: MVC 4

Internet Application:Contains the beginnings of an MVC web application, including

basic account management functions that use ASP.NET Membership.

Intranet Application:Added in ASP.NET MVC 3 tools update. Similar to the

Internet Application template, but the account management functions use Windows accounts rather than ASP.NET Membership.

Basic Template:Minimal. Has basic folders, CSS, and MVC application

infrastructure in place, but no more. You need to do work in order to get the application to run. For experienced MVC developers that don’t want the predefined items in the project.

Cont.

Page 33: MVC 4

Empty:Only has the assemblies and the basic folder

structure in placeMobile Application:

Preconfigured with jQuery Mobile.Includes mobile visual themes, a touch-

optimized UI, and support for Ajax navigationWeb API template:

Similar to the Internet Application template but is streamlined for Web API development

Cont.

Page 34: MVC 4

ASPX Razor

View Engines

Page 35: MVC 4

Just check the box!

You can add other Test Frameworks like NUnit, MbUnit, or xUnit if you want to.

http://msdn.microsoft.com/en-us/library/dd381614.aspx

Testing

Page 36: MVC 4

Controllers – Controller classes that handle URL request go here (MVC 4, controller classes can go anywhere)

Models – Classes that represent and manipulate data and business objects go here

Views – UI template files that are responsible for rendering output go here

Scripts – JavaScript files and scripts go hereImages – images used on your site go here

MVC Application Structure

Page 37: MVC 4

Content – CSS and other site content, other than images and scripts, goes here

Filters – Filter code goes hereApp_Data – Store data files that you read and

write to, hereApp_Start – Configuration code for features

like Routing, Bundling and Web API goes here

Cont.

Page 38: MVC 4

ASP.NET MVC does not require this Directory Structure.

Page 39: MVC 4

“Convention over configuration”ASP.NET MVC is heavily convention-based

Uses Directory-naming structure when resolving view templates.Allows you to omit the location path when

referencing views from within a Controller class.

Conventions

Page 40: MVC 4

Each controller’s class name ends with ControllerLegalController, LegalServicesController,

HomeControllerOne Views directory for all the views of your

applicationViews that controllers use live in a subdirectory of

the Views main directory and are named according to the controller name(minus the Controller suffix)Views for the LegalController would live in

/Views/LegalReusable UI elements live in a similar structure,

but in a Shared directory in the Views folder

Cont.

Page 41: MVC 4

2. Controllers

Page 42: MVC 4

Model View Controller: 1st Controller basics, then the other stuff.Have a look at the HomeController

Responsible for deciding what will happen when you browse to the homepage of the website.

Controller Basics

Page 43: MVC 4

Responsible for responding to user input, making changes to the model in response to user input if needed.

Controllers are concerned with the flow of the application, working with data that comes in and providing data going out to the relevant view.

The Controller’s Role

Page 44: MVC 4

The URL tells the routing mechanism (later chapter) which controller class to instantiate and which action method to call, and supplies the required arguments to that method.

The controller’s method then decides which view to use, and that view then renders the HTML.

The controller’s method could return something other than a view.

Cont.

Page 45: MVC 4

There is a relationship between the URL and the METHOD on a controller class. Not a relationship between the URL and a FILE on the web server.

MVC serves up the results of method calls, not dynamically generated pages.

(More about routing in later chapter)

Cont.

Page 46: MVC 4

IController

Page 47: MVC 4

ControllerBase

Page 48: MVC 4

Controller Class

Page 49: MVC 4

Add additional methods for additional scenarios.These methods are called Controller Actions

or Action MethodsThey respond to URL request, perform the

appropriate actions, and return a response back to the browser or user that invoked the URL

Controller Actions

Page 50: MVC 4

MVC Request processing pipeline

Page 51: MVC 4

• The Browse and Details methods to cover additional scenarios.

Modifying the LegalServicesController

Page 52: MVC 4

Browsing to /LegalServices/Browse caused the browse method of the LegalServicesController to be executed. NO extra configuration was needed. This is routing in action. More later

We created the controller class which was very simple. Inherits from System.Web.Mvc.Controller

We returned text to the browser without a model or a view.

Observation

Page 53: MVC 4

/LegalServices/Details/5 vs. /LegalServices/Details?ID=5

The default routing convention in MVC will automatically pass the URL segment to you as a parameter. The default parameter is named “ID”

If your parameter is not “ID” then use the “?” or configure routing.

Cont.

Page 54: MVC 4

The previous example was not common and was oversimplified. You will almost always use ViewsYou will most often return ActionResult instead

of stringsAnd routing is more complex that shown.

Oversimplified

Page 55: MVC 4

Controllers orchestrate the interactions of the user, the model objects and the views.

They are responsible for:responding to the user inputManipulating the appropriate model objectsAnd then selecting the appropriate view to

display back to the user in response to the initial input

Basic Controllers Summary

Page 57: MVC 4

ActionResult type

Page 58: MVC 4

3. Views

Page 59: MVC 4

The user’s first impression of your site starts with the View

Responsible for providing the user interface to the user.

The view transforms a model into a format ready to be presented to the user.

The view examines the model object and transforms the contents to HTML

The View

Page 60: MVC 4

Note:Not all views render HTML, but HTML is the

most common caseMore info on alternate types of content later.

Cont.

Page 61: MVC 4

Example

Page 62: MVC 4

The Views directory contains a folder for your controller, with the same name as the controller, but without the controller suffix.[Take a look]

HomeController has views in the Home directoryWithin the view folder (also called controller folder)

there’s a view file for each action method, named the same as the action method.

This is how views are associated to an action method.

An action method can return a ViewResult via the View() method.

Convention

Page 63: MVC 4

When the view name isn’t specified, the ViewResult returned by the action method applies a convention to locate the view. It first looks for a view with the same name as the action

within the /Views/ControllerName directory. “Ex: /views/home/Index.cshtml”

The View() method is overloaded. You can supply a view name to render a different view. “ex: View(“MyView”)” It will still look in the same directory, but will look for the

“MyView.cshtml” file.View(“~/Views/DifferentDirectory/Index.cshtml”)

To get to a different directory, provide the full path to that directory. You must provide the file extension as well. This bypasses the internal lookup mechanism.

View() Method

Page 64: MVC 4

Passing information from the Controller to the View Data is passed from the controllers to the views via a

ViewDataDictionary (a specialized dictionary class) called ViewData. You can use standard dictionary syntax: ViewData[“CurrentTime”] =

DateTime.Now; ViewBag is a dynamic wrapper around ViewData

The ViewBag leverages the C# 4 keyword “dynamic” The syntax is simplified:

ViewBag.CurrentTime = DateTime.Now; Note:

@Html.TextBox(“name”, ViewBag.Name) won’t compile because of the dynamic type.

Try: @Html.TextBox(“name”, (string)ViewBag.Name) or use

ViewData[“Name”] instead See page 51 Note

ViewData and ViewBag

Page 65: MVC 4

Create a simple View

Exercise

Page 66: MVC 4

You can add a collection or list of items to the ViewBag:

Strongly Typed Views

Page 67: MVC 4

Instead of adding a collection or list of items to the ViewBag and passing it to the view, and then iterating through it in the view, the ViewData object has a Model property that can be set by using the overload of the View() method.

Cont.

Page 68: MVC 4

Cont.

Page 69: MVC 4

To make it easier to deal with the class names you can add a namespace by using the @using MyApp.Models (foldername)

Or if used frequently add the namespace to the web.config

Namespaces

Page 70: MVC 4

There can be only one model in the ViewData.Model objectWhat happens if you need additional items that

aren’t in the Model object?You could add that data to the ViewBag and be

done, but not everyone likes this

View Models

Page 71: MVC 4

View Model A better name would be (View Specific Model)Not MVVM

Used to display a variety of data that comes from different places. Aggregating data into a single Model that can be used by a view.

Ex: Case Info, Lawyer Info, and User Info that needs to be displayed by a single View

You could also just add the info to a ViewBag and skip creating a View ModelIt would work but it wouldn’t be strongly typed

Cont

Page 72: MVC 4

Cont.

Page 73: MVC 4

View NameView EngineCreate a strongly-typed viewModel ClassScaffold TemplateReference Script LibrariesCreate a partial viewUse a layout or master page

ViewStart.cshtml

The Add View dialog

Page 74: MVC 4

Empty Creates an empty view. Only the model type is specified using the @model syntax

Create Creates a view with a form for creating new instances of the model. Generates a

label and input field for each property of the model type Delete

Creates a view with a form for deleting existing instances of the model. Displays a label and the current value for each property of the model

Details Creates a view that displays a label and the value for each property of the model

type Edit

Creates a view with a form for editing existing instances of the model. Generates a label and input field for each property of the model type.

List Creates a view with a table of model instances. Generates a column for each

property of the model type. Makes sure to pass an Ienumerable<yourModelType> to this view from your action method. The view also contains links to actions for performing the create / edit / delete operations

Scaffold Template

Page 75: MVC 4

This option is used to indicate whether the view your are creating should include references to a set of JavaScript files if it makes sense for the view.

By default, the _Layout.cshtml file references the main jQuery library, but doesn’t reference the jQuery Validation library or the Unobtrusive jQuery Validation library.

Check the box to reference these libraries when doing Edit view, or Create view.

Reference Script Libraries

Page 76: MVC 4

A partial view is not a full view. The layout option will be disabled if you

select this optionNo <html> tag or <head> tag at the top of

the view

Create as a Partial View

Page 77: MVC 4

Determines whether or not the view you are creating will reference a layout (or master page) or will be self-contained.

For Razor view engines, specifiying a layout is not necessary if you choose to use the default layout because the layout is already specified in the _ViewStart.cshtml file.

This option can be used to override the default Layout file.

Use a Layout or MasterPage

Page 78: MVC 4

What is Razor?Introduced in ASP.NET MVC 3 and is the

default view engine moving forwardProvides a clean, lightweight, simple view

engine.Provides a streamlined syntax for expressing

viewsMinimizes the amount of syntax and extra

characters.

Razor View Engine

Page 79: MVC 4

Cont.

Page 80: MVC 4

C# syntax has the .cshtml file extentionVB - .vbhtml

File Extension signals that the Razer parser should be used

Cont.

Page 81: MVC 4

Just type the @ symbol in the HTML and insert some code

The @ symbol is used to transition from markup to code and sometimes to transition back to markup

@{}@(item).Models@@ to escapeUse parenthesis whenever there is ambiguity

@

Page 82: MVC 4

Razor expressions are automatically HTML encoded. This is great for mitigating XSS

@{string message = “<script>alert(‘hi

there’);</script>”;}<span>@message</span>This statement will not create an alert box

HTML Encoding

Page 83: MVC 4

You can use the HTML.Raw() method to return a string that Razor will not encode.

You can also create an instance of HTMLString

HTML.Raw()

Page 84: MVC 4

Cont.

Page 85: MVC 4

Razor’s automatic HTML encoding is not sufficient for displaying user input within JavaScript

When setting variables in JavaScript to values supplied by the user, it’s important to use JavaScript string encoding and not just HTML encoding.

http://localhost:49693/home/escript?name=Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%20\x3c/script\x3e

http://localhost:49693/home/escript?name=<script>alert('bob')</script>

@Ajax.JavaScriptStringEncode

Page 86: MVC 4

Ref: page 63@{}

Code blocks

Page 87: MVC 4

<Span>@Model.Message</span>Code expressions are evaluated and written

to the response.Code expressions are always HTML encoded

Implicit Code Expression

Page 88: MVC 4

<span>Product ID: @(PID)<span>

Explicit Code Expression

Page 89: MVC 4

<span>@Html.Raw(model.Message)</span>

Unencoded Code Expression

Page 90: MVC 4

@{int x = 900;string y = “bob is cool”;

}

Blocks of code are simply sections of code that are executed.

Useful for declaring variables that you may need in your code later

Code Block

Page 91: MVC 4

@foreach(var item in items){<span>Item: @item.Name.</span>

}

Combining Text and Markup

Page 92: MVC 4

@if(showMessage){<text>This is plain text</text>

}

@if (showMessage){this is plain text.

}

Mixing Code and Plain Text

Page 93: MVC 4

@* *@

Server-side comments

Page 94: MVC 4

@(Html.Amethod<TheType>())

Use parenthesis just like with explicit code expressions.

Calling a Generic Method

Page 95: MVC 4

Same purpose as MasterPagesMaintain a consistent look and feel across

multiple views within your applicationSimpler syntax that MasterPages and greater

flexabilityContains one or more placeholders that the

other views can provide content for.

Layouts

Page 96: MVC 4

Cont.

Page 97: MVC 4

Looks like a standard Razor view, but has specific place holders.

@RenderBodyPlaceholder where views using this layout will

have their main content rendered.

Cont.

Page 98: MVC 4

@RenderSection(“Footer”) @RenderSection(“Footer”, required:false)

@section Footer{This is <i>footer</i> content!

}

@if(IsSectionDefined(“Footer”)){RenderSection(“Footer”);

}Else{

<span>Some default content</span>}

Or use Templated Razor Delagates (Page 392 (Later))

Cont.

Page 99: MVC 4

_ViewStart.cshtmlSpecifies the default layoutAny view can override this layout and choose a

different one.

ViewStart

Page 100: MVC 4

Return a Partial View in the form of a PartialViewResult via the PartialView() method.

A Partial View does not specify a layoutUseful in partial update scenarios using AJAX.

Partial View

Page 101: MVC 4

4. Models

Page 102: MVC 4

An object that represents the data in the application.

Often corresponds to tables in the database, but they don’t have to.

Controller action methods which return an ActionResult can pass a model object to the view.

The Model

Page 103: MVC 4

You may need to figure out what the model should represent or how it should be implemented. This may be based on business requirements or conversations with business owners or customers.

What problem are you trying to solve?List? Edit? Create? Delete?

Cont.

Page 104: MVC 4

Generates the boilerplate code you need for create, read, update, and delete (CRUD) functionality in an application.

Scaffolding templates can examine the type definition for a model, then generate a controller and the controller’s views.

It knows how to name the controllers, how to name the views, what code needs to go in each component, and where to place all the pieces within the project.

It takes care of the boring work

Scaffolding

Page 105: MVC 4

Empty ControllerController with Empty Read/Write actionsAPI Controller with Empty Read/Write

ActionsController with Read/Write actions and

Views, using Entity Framework

Scaffolding templates

Page 106: MVC 4

Class that derives from ControllerIndex is the only action in the controller, with

not code inside

Empty Controller

Page 107: MVC 4

Adds a controller with Index, Details, Create, Edit, and Delete

You still need to add code to make it work

Controller with Empty Read/Write actions

Page 108: MVC 4

Derived from ApiController base class. You can use this class to build a Web API for

your application

API Controller with Empty Read/Write Actions

Page 109: MVC 4

Generates the controller with Index, Details, Create, Edit and Delete actions

Also Generates all the required views and code to persist and retrieve information from a database.

When you select the model class, the scaffolding examines all the properties of your model and uses the info to build controllers, views, and data access code.

To generate the Data Access Code, the scaffolding also needs the name of the DataContext object, if it exist. If not the scaffolding can create one for you.

Controller with Read/Write actions and Views, Using Entity Framework

Page 110: MVC 4

Entity Framework (EF) is and object-relational mapping framework.

It understands how to store .NET objects in a relational database and retrieve those same objects given a LINQ query.

Scaffolding and EF

Page 111: MVC 4

EF supports a Code-First style of development Start storing and retrieving information in SQL server

without creating a database schema or opening a Visual Studio designer

Write .NET classes and EF figures out how, and where, to store instances of those classes.

This is why your properties in your model object are virtual.

Marking them as virtual, gives EF a hook into your classes and enables features like an efficient change tracking mechanism.

EF needs to know when a property value on a model changes, in case it needs to update the datasource.

Code First

Page 112: MVC 4

Model-firstSchema-firstBoth supported along with code-first

Database first or Code first

Page 113: MVC 4

If you have a class named Laywer, EF will create a table named Laywers

If you have a property named LawyerId, EF will assume that it’s the Key value

This too is by convention

Code First Conventions

Page 114: MVC 4

Derive from the DbContext classOne or more properties of type DbSet<t>t is the type of object you want to persist

Public class LegalDB : DbContext{

public DbSet<Laywer> Lawyers { get; set;}

public DbSet<Case> Cases { get; set;}}

DbContext Class

Page 115: MVC 4

The DbContext can be created manually or automatically via the create controller dialog

Cont.

Page 116: MVC 4

Change to Virtual Methods for EF

Cont.

Page 117: MVC 4

Overview of LINQOverview of Lamda

LINQ

Page 118: MVC 4

Eager loading:var jails = db.Jails.Include(j => j.Cells);Brings all of the related objects on the first call

Lazy LoadingBrings all of the related objects when touchedBut this can cause a query for every item

touched20 Jails with could cause 21 extra queries to

the databaseNote: page 80

Eager vs. Lazy Loading

Page 119: MVC 4

The Scaffolding created views in the appropriate folder

Index, edit, delete, details, create

The Views

Page 120: MVC 4

Examine the views that were created by the scaffolding

Make changes

Examine the views

Page 121: MVC 4

In Code-first, EF attempts to use convention over configuration as much as possible.

If you don’t configure specific mappings from your models to database tables and columns, EF uses conventions to create a database schema.

If you don’t configure a specific db connection to use at runtime, EF creates on using a convention.

EF and the Database

Page 122: MVC 4

To allow the EF to re-create an existing database:

DropCreateDatabaseAlwaysDropCreateDatabaseIfModelChanges

System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<JLegal.Models.JailDB3Context>());

Database Initializer

Page 123: MVC 4

EF 4.3 includes the ability to discover the changes you’ve made to the model objects and generate schema change instructions for SQL Server.

Migration allows you to preserve existing data in your database as you build and refine your model definitions

http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx

http://msdn.microsoft.com/en-US/data/jj591621

Migrations

Page 124: MVC 4

Derive from the DropCreateDatabaseAlways class and override the Seed method.

Use the new class in the SetInitializerNote: 84 -85

Seeding a Database

Page 125: MVC 4

Cont.

Page 126: MVC 4

Changing the Edit View

Page 127: MVC 4

Get and Post

Page 128: MVC 4

In previous code:ModelState:

The model knows if it is valid or notEntityState

Next pagedb.SaveChangesRedirectToAction(“Index”)

ModelState

Page 129: MVC 4

EntityState

Page 130: MVC 4

No more reading from the Request.Form Collection unless you want to.

Naming convention takes care of it allDefaultModelBinder

Automatically converts the Form info to the Model object based on naming convention.

It uses the Request not just the Form Collection. It looks at route data, the querystring, and the Form

Collection and custom value providers if needed.Page 91

Model Binding

Page 131: MVC 4

Using the DefaultModelBinder

Page 132: MVC 4

You can have multiple model binders registered in the MVC runtime for different types of models, but the defaultModelBinder may work for you.

The default uses naming conventions to find the matches.

If it sees a FirstName property it looks for a FirstName value in the request. It uses “value providers” to search for the

values in different parts of the request.

Cont.

Page 133: MVC 4
Page 134: MVC 4

Explicit Model Binding

Page 135: MVC 4

Cont

Page 136: MVC 4

5. Forms and HTML Helpers

Page 137: MVC 4

Action tells the web browser where to send the information

MethodGet

Send info in the headerViewable in the Querystring

Post Send info in the BodyNot Viewable in the Querystring

Form Tag: Action and Method

Page 138: MVC 4

Html Helpers are methods you can invoke on the Html property of a view.

Url HelpersAlso available from the controller

Ajax Helpers

Make views easy to author.

@using (Html.BeginForm(“Search”, “Home”, FormMethod.Get))

HTML Helpers

Page 139: MVC 4

Html.BeginForm

Page 140: MVC 4

All helpers that output model values will automatically HTML encode the values before rendering.

Automatic Encoding

Page 141: MVC 4

Cont.

Page 142: MVC 4

System.Web.Mvc.HtmlHelper<t>Several items implemented as extension

methods by the frameworkSystem.Web.Mvc.Html Namespace

Note:Views/web.config has the namespace entry

Extension methods

Page 143: MVC 4

Displays an unordered list of all validation errors in the ModelState dictionary

Html.ValidationSummary

Page 144: MVC 4

ModelState.AddModelError(“”, “wrong”);Model-level error (no key)

ModelState.AddModelError(“Title”, “Bad Name); Property-Level (key provided)

ModelState.AddModelError

Page 145: MVC 4

Cont.

Page 146: MVC 4

http://msdn.microsoft.com/en-us/library/dd410596(v=VS.98).aspx

List of HTML Helpers

Page 147: MVC 4

Html.ActionLink

Page 148: MVC 4

Html.Checkbox

Page 149: MVC 4

Html.Label

Page 150: MVC 4

Difference betweenHtml.LabelHtml.LabelFor

Works with a modelNot to be confused with the “for” attribute

Cont.

Page 151: MVC 4

Html.DropDownList and Html.ListBox

Page 152: MVC 4

Html.TextBox and Html.TextArea

Page 153: MVC 4

Html.ValidationMessage

Page 154: MVC 4

Set the value via the ViewBag

Page 155: MVC 4

Cont.

Page 156: MVC 4

Cont.

Page 157: MVC 4

Strongly typed Helpers

Page 158: MVC 4

Helpers and Model Metadata

Page 159: MVC 4

Templated helpers provide a way to automatically build UI based on a data model that is marked with attributes defined in the System.ComponentModel.DataAnnotations namespace.

Templated Helpers Html.Display Html.Editor

Strongly Typed Templated Helpers Html.DisplayFor Html.EditorFor

Whole-Model Templated Helpers Html.DisplayForModel Html.EditorForModel

Templated Helpers

Page 160: MVC 4

Use Html.EditorFor to render the same HTML as TextBoxFor, however, you can change the HTML using data annotations.

Cont.

Page 161: MVC 4

ModelState is a byproduct of model binding and holds all validation errors detected during model building.

Also holds the raw values the user submits to update a model.

Helpers used to render form fields automatically look up their current value in the ModelState dictionary. If the value exists in the ModelState, the helper uses the value from the ModelState instead of a value in the view data.

User enters “Bob” into the Price fields and submits, when the view is returned to the user because the model binding failed, the user will still see “Bob”

When ModelState contains an error for a given property, the form helper associated with the error renders a CSS class of input-validation-error (red)

ModelState and Helpers

Page 162: MVC 4

Html.Hidden

Page 163: MVC 4

Html.Password

Page 164: MVC 4

Html.RadioButton

Page 165: MVC 4

Html.CheckBox

Page 166: MVC 4

Html.ActionLinkHtml.RouteLink

Rendering Helpers

Page 167: MVC 4

ActionExactly like ActionLink but does not return an

anchorContent

Can convert a relative application path to an absolute application path

RouteUrlSame pattern as Action, but accepts a route

name like RouteLink

Url Helpers

Page 168: MVC 4

Html.PartialRenders partial view to a string.

Html.RenderPartialRenders partial view to the response output

stream instead of returning a string.

Html.Partial and Html.RenderPartial

Page 169: MVC 4

ActionExecutes a separate controller action and

displays the resultRenderAction

Writes directly to the response

[ChildActionOnly]

Html.Action and Html.RenderAction

Page 170: MVC 4

Cont.

Page 173: MVC 4

Cont.

Page 174: MVC 4

6. Data Annotations and Validation

Page 175: MVC 4

an unobtrusive validation library built on top of jquery.validation MVC comes with support for Data Annotations (that is,

System.ComponentModel.DataAnnotations) and can be extended becoming more popular and is being baked in to many other

Microsoft offerings, including Entity Framework MVC only contains four validators: Range, Required,

StringLength and Regular Expression The Data Annotations Extensions project can be found at 

http://dataannotationsextensions.org/, and currently provides 11 additional validation attributes (ex: Email, EqualTo, Min/Max) on top of Data Annotations’ original 4.

.NET 4.5 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx

Data Annotation

Page 176: MVC 4

NuGet packages

Page 177: MVC 4

System.ComponentModel.DataAnnotations namespace (some in other namespaces)

Provide Server-side validationThe framework also supports client-side

validation when you use one of the attributes on a model property

There are 4 attributes in this namespace

Using Validation Annotations

Page 178: MVC 4

Creates a required valueRaises a validation error if the property value

is null or emptyClient and server-side logic (although client-

side validation is actually through a validation adapter design)

If the client does not have JavaScript enabled in the browser, the validation logic will catch the it on the server, too. The user will still see the error.

[Required]

Page 179: MVC 4

[StringLength]

Page 180: MVC 4

[Phone][EmailAddress][CreditCard]

[RegularExpression]

Page 181: MVC 4

[Range]

Page 182: MVC 4

System.Web.Mvc namespace

[Remote]

Page 183: MVC 4

[Compare]

Page 184: MVC 4

Custom Error Messages

Page 185: MVC 4

By default, the MVC framework executes validation logic during model binding.

Part of a system of model binders, model metadata, model validators and model state.

The model binder runs implicitly when you have parameters to an action method

Validation and Model Binding

Page 186: MVC 4

UpdateModel / TryUpdateModel

Page 187: MVC 4

Once the model binder is finished updating the model properties with new values, the model binder uses the current model metadata and ultimately obtains all the validators for the model.

DataAnnotationsModelValidatorA model validator that can find all the validation

attributes and execute the validation logic inside. The model binder catches all the failed

validation rules and places them into the Model State

Cont.

Page 188: MVC 4

Model binding produces model state.Model state is accessible in a Controller-

derived object using the ModelState propertyModel state contains all the values the user

attempted to put into model propertiesModel state also contains all the errors

associated with each property, and errors associated with the model itself.

If there is an error in model state Model.IsValid returns false

Validation and Model State

Page 189: MVC 4

Cont.

Page 190: MVC 4

Valid or not?

Page 191: MVC 4

TryUpdateModel

Page 192: MVC 4

Many possibilities:Package validation logic into a custom data

annotationPackage validation logic into the model itself

(self-validating model)

Custom Validation Logic

Page 193: MVC 4

Derive from ValidationAttribute base classSystem.ComponentModel.DataAnnotations

namespace

Custom Annotations

Page 194: MVC 4

Override the IsValid methodAdd a constructor

Cont.

Page 195: MVC 4

Pass the error message to the base class.

Cont.

Page 196: MVC 4

Allow for custom error message

Cont.

Page 197: MVC 4

Cont.

Page 198: MVC 4

IValiatableObject

Page 199: MVC 4

Cont.

Page 200: MVC 4

Display a friendly name to the UI

[Display]

Page 201: MVC 4

The default order is 10000Fields appear in ascending order

Cont.

Page 202: MVC 4

ScaffoldColumn

Page 203: MVC 4

[DisplayFormat]

Page 204: MVC 4

ReadOnly

Page 205: MVC 4

[DataType]

Page 206: MVC 4

[UIHint]

Page 207: MVC 4

[HiddenInput]

Page 208: MVC 4

http://msdn.microsoft.com/en-us/library/hh390735.aspx

[ForeignKeyAttribute][TabletAttrubute]

[DatabaseGenerate]

Page 209: MVC 4

7. Security

Page 210: MVC 4

Threats:Cross-Site Scripting XSSCross-Site Request ForgeryOver-PostingOpen Redirection

Security Vectors in a web app

Page 211: MVC 4

Asynchronous JavaScript and XMLThe core of the support for Ajax in the

ASP.NET MVC 4 framework comes from the jQuery JavaScript library

8. Ajax

Page 212: MVC 4

jQuery is added to your project by the Template you selected.

Scripts folderAdded by NuGet

Can easily upgrade scripts when a new version of jQuery arrives

jQuery

Page 213: MVC 4

jQuery function (aliased as the $ sign)Less typing

jQuery Features

Page 214: MVC 4

jQuery Selectors

Page 215: MVC 4

You can subscribe to events

jQuery Events

Page 216: MVC 4

jQuery Method Chaining

Page 217: MVC 4

Shortcuts

Page 218: MVC 4

jQuery includes what you need to send asynchronous request back to your server.

You can generate Post or Get request and jQuery will notify you when the request is complete (error or not)

Consume XML, HTML, Text or JSON

jQuery and Ajax

Page 219: MVC 4

Keeping the JavaScript code separate from markup

Unobtrusive JavaScript

Page 220: MVC 4

Using jQuery

Page 221: MVC 4

Create a .js file in the scripts folderAdd a <script> tag to the viewMust come later than the jQuery script tag

Cont.

Page 222: MVC 4

Modernizes old browsers. Enables HTML 5 elements on browsers that

don’t support HTML 5Also detects other features like geolocation

and the drawing canvas if available.

Modernizr

Page 223: MVC 4

Add a reference to :

Ajax Helpers

Page 224: MVC 4

A Razor view has an Ajax property available

Ajax ActionLinks

Page 225: MVC 4

Data “dash” attributes

HTML 5 Attributes

Page 226: MVC 4

Ajax Forms

Page 227: MVC 4

Client side validation

Page 228: MVC 4

Cont.

Page 229: MVC 4

Cont.

Page 230: MVC 4

IClientValidatable

Page 231: MVC 4

Cont.

Page 232: MVC 4

Cont.

Page 233: MVC 4

jQuery UI

Page 234: MVC 4

jQuery UI examples

Page 235: MVC 4

9. Routing

Page 236: MVC 4

Your MVC application needs at lease one route to define how the app should handle request.

You can have many routes in your application.

Defining Routes

Page 237: MVC 4

Global.asax.csRouteConfig.RegisterRoutes(RouteTable.Route

s);App_Start folder:

Cont.

Page 238: MVC 4

url segments A segment is everything between slashes but

not including the slashesUrl Parameters

Each contains a parameter in curly bracesThis is a pattern matching rule

Cont.

Page 239: MVC 4

“{controller}/{action}/{id}”{controller} is used to instantiate a controller

class to handle the request. MVC appends the suffix “Controller” to the value of the {controller} URL parameter and attempts to find a type of that name.

{action} is used to indicate which method of the controller to call in order to handle the current request.

{id} looks for a parameter named id

Cont.

Page 240: MVC 4

Cont.

Page 241: MVC 4

Optional values

Page 242: MVC 4

@Html.RouteLink("blog", new{controller="Blog", action="Index“, year=2341, month=23, day=34})

http://[domain name]/2012/02/24

Cont.

Page 243: MVC 4

Allow you to divide your models, views, and controllers into separate functional sections.

Separate larger or complex sites into sections Each Area will have its own set of folders for

controllers, views, models Each area will have its own routing registration

Derive a class from the AreaRegistration classOverride AreaName and RegisterArea

MVC Areas

Page 244: MVC 4

Demo:Create two Areas

Cont.

Page 245: MVC 4

Each area has its own routing registration

Cont.

Page 246: MVC 4

Area route conflicts

Page 247: MVC 4

Catch-all parameter

Page 248: MVC 4

cont

Page 249: MVC 4

URL Generation

Page 250: MVC 4
Page 251: MVC 4
Page 252: MVC 4

Overflow parameters

Page 253: MVC 4

Routing is not looking for an exact match. Just a sufficient match.

Extra parameters will be placed in the querystring prameters (after the ?)

Cont.

Page 254: MVC 4

HTML 5

Page 256: MVC 4

NuGet and Packages

Page 257: MVC 4

HTTP services on top of the .NET frameworkShips with MVC 4Why?

Reach more clientsXml, json,

Scale with the cloudEmbrace HTTP

Simplify communication with clients

Web API

Page 258: MVC 4
Page 259: MVC 4

Dependency Injection

Page 260: MVC 4

A software design patternTypes of Patterns in use today

Inversion of ControlService Locator

Weakly Typed Service LocatorStrongly Typed Service Locator

Dependency InjectionConstructor InjectionProperty Injection

What is Dependency Injection?

Page 261: MVC 4

Coupling / Tightly CouplingWhen a component has a dependency.

Ex: creating an instance of class “A” within the constructor class “B”

Class “B” can’t work if class “A” (the dependency) isn’t available.

Your class knows exactly what kind of class it needs to use.

Makes it hard or impossible to use a different type of the same class.

Changes to the class “A” may break class “B”What if you wanted to use class “C” instead of class

“A”?

Coupling

Page 262: MVC 4

Moving the responsibility for creating the instance of the class (Class A) outside of the class (Class B) that consumes the dependency

2 steps:Create a layer of abstraction

InterfaceMove the responsibility for creating the

instance outside of the consuming classPass the class via the constructor or a propertyOr use a Service locator

Inversion of Control

Page 263: MVC 4

An external component that finds the service (class) that you are looking for. Your class relies on the locator to always give it back the correct type. Your class doesn’t care what type it is because it expects a type that has implemented the correct interface.

Good for unit testing

Strongly Typed Service Locator

Page 264: MVC 4

Similar to the Strongly typed service locator but returns object instead of a specific interface

Your class must cast to the correct type of interface

You could create a Generic Type as well

Weakly Typed Service Locator

Page 265: MVC 4

This pattern is a type of Inversion of ControlNo service locatorGood for testing

Constructor Injection:Pass the dependency into the constructor

Property Injection:Pass the dependency into a property

Dependency Injection

Page 266: MVC 4

Acts as a factory for components, inspecting and fulfilling their dependency requirements

A little different than a service locatorService locator:

If anyone asks for this type, give them this objectDIC:

If anyone asks for this type, you create an object of this concrete type and give them that

Dependency Injection Container