ASP.NET MVC 2.0

53
ASP.NET MVC 2.0 10/29/2010

description

Training slides for Microsoft customers

Transcript of ASP.NET MVC 2.0

Page 1: ASP.NET MVC 2.0

ASP.NET MVC 2.0

10/29/2010

Page 2: ASP.NET MVC 2.0

Buu Nguyen

• Microsoft MVP, MCSD.NET, SCJD, SCBCD

• Vice President of Technology, KMS Technology

• Lecturer, RMIT University Vietnam

Page 3: ASP.NET MVC 2.0

Table of Contents

Core

• ASP.NET MVC Basics

• Routing

• Controllers & Action Methods

• View Results & Views

Advanced

• Action Method Selectors

• Filters

• Model Validation

• Model Templates

• And beyond…

Page 4: ASP.NET MVC 2.0

ASP.NET MVC BASICS

Page 5: ASP.NET MVC 2.0

Overview of ASP.NET MVC

• MVC-based .NET web development platform

• Alternative, not replacement, for Web Forms

• Built openly & iteratively

(http://www.codeplex.com/aspnet)

• Releases

• Latest RTM release is ASP.NET MVC 2.0

• Latest release is ASP.NET 3.0 Beta

Page 6: ASP.NET MVC 2.0

Technology Stack

ASP.NET Web

Forms ASP.NET MVC

ASP.NET Framework (Configuration, Security, Membership, Roles, Profiles, Routing, Caching,

Session, Application State, Cookie, .aspx/.ascx/.asax/.master files etc.

.NET Framework

Page 7: ASP.NET MVC 2.0

ASP.NET MVC Pros & Cons

Advantages

• Clear separation of

concerns

• Testability & TDD

• Tight-control over markup

• Extensibility

• Search-engine

friendliness

• Good parts of ASP.NET

Disadvantages

• No out-of-the-box rich UI

helper methods

• Learning curve is (a bit)

stiffer than Web Forms

• Community is not yet as

crowded as Web Forms

Page 8: ASP.NET MVC 2.0
Page 9: ASP.NET MVC 2.0

Project Structure • Project Conventions

• Content: CSS, images etc.

• Controllers: controller classes

• Models: model classes

• Views

• [Controller]: controller-specific views

• Shared: master pages, user controls, shared views etc.

• Scripts: JavaScript files

Page 10: ASP.NET MVC 2.0

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

Page 11: ASP.NET MVC 2.0

About TodoApp

• Allow users to manage tasks

• To spend our time wisely, we‟ll: • Utilize the Membership API for user management

• Use Entity Framework for DB logic

Page 12: ASP.NET MVC 2.0

Let’s see the completed TodoApp

Page 13: ASP.NET MVC 2.0

ROUTING

Page 14: ASP.NET MVC 2.0

Overview

• Enabled by UrlRoutingModule

• Introduced since ASP.NET 3.5 SP1

• Independent from ASP.NET MVC

• Responsibilities

• Map incoming URLs to route info

• Construct outgoing URLs from route info

Page 15: ASP.NET MVC 2.0

Incoming URL to Route Info

actual value becomes

TaskController.cs

Page 16: ASP.NET MVC 2.0

Route Constraints

• Strings (regular expression)

• Classes implementing IRouteConstraint E.g. HttpMethodConstraint

Custom constraints

Page 17: ASP.NET MVC 2.0

Outgoing URLs & Links • Generate outgoing URL from route info

• UrlHelper#Action(…)

• Generate outgoing link from route info • HtmlHelper#ActionLink(…)

Page 18: ASP.NET MVC 2.0

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

Page 19: ASP.NET MVC 2.0

CONTROLLERS & ACTION METHODS

Page 20: ASP.NET MVC 2.0

Controllers

• Usually inherit from Controller class

• Can directly inherit from IController interface

• Usually correspond to an entity or domain concept

• Instantiated by a controller factory

• Can create a custom controller factory (e.g. to apply dependency

injection)

Page 21: ASP.NET MVC 2.0

Action Methods

• Public methods of a controller

• Each action method corresponds to 1 HTTP request &

response

• Input sources for action methods

• Context objects

• Parameters

• Output of action methods is an object implementing ActionResult interface

Page 22: ASP.NET MVC 2.0

Input #1 – Common Context Objects

• Request.QueryString

• Request.Form

• Request.Cookie

• Request.Headers

• HttpContext.Application

• HttpContext.Session

• HttpContext.Items

• HttpContext.Cache

• RouteData.Values

• User

• Authentication info of the current user

• TempData

• Data stored in the previous request in the same session

• etc.

Page 23: ASP.NET MVC 2.0

Input #2 – Action Method Parameters

• Action methods have their parameters supplied from the following sources • Request.QueryString

• Request.Form

• RouteData.Values

• Complex-typed parameters can be supplied too • This is called model binding

• It‟s possible to implement custom model binders

Page 24: ASP.NET MVC 2.0

Action Method Results

• Action methods return objects implementing ActionResult

• Each subclass overrides ExecuteResult() method to work with

the Response object

• Send file, redirect, render HTML etc.

• It‟s possible to implement custom action result

Page 25: ASP.NET MVC 2.0

Built-in Action Result Types Action Result Type Examples of Use (in action methods)

ViewResult return View();

return View(“view”, modelObject);

PartialViewResult return PartialView();

return PartialView(“partialview”, modelObject);

RedirectToRouteResult return RedirectToRoute(“LogOn”);

RedirectResult return Redirect(“http://www.microsoft.com”);

ContentResult return Content(rss, “application/rss+xml”);

FileResult return File(“chart.ppt”, “application/ppt”);

JsonResult return Json(someObject);

JavaScriptResult return JavaScript("$(„#table‟).init();");

HttpUnauthorizedResult return new HttpUnauthorizedResult();

EmptyResult return new EmptyResult();

ActionResult Base class for all action results, including custom ones

Page 26: ASP.NET MVC 2.0

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

Page 27: ASP.NET MVC 2.0

VIEW RESULTS & VIEWS

Page 28: ASP.NET MVC 2.0

ViewResult

• The call to View(…) generates a ViewResult object

• ViewResult lookups a view engine to render the content

• The default view engine is WebFormViewEngine

• ASP.NET MVC 3 is shipped with the Razor view engine

• Custom view engines for XSLT, Brail, NHaml, etc. are available

• View path lookup

• Either View("~/path/to/some/view.aspx");

• Or if controller (& action) are specified

• /Views/ControllerName/ViewName.aspx

• /Views/ControllerName/ViewName.ascx

• /Views/Shared/ViewName.aspx

• /Views/Shared/ViewName.ascx

Page 29: ASP.NET MVC 2.0

ViewData

• Controllers pass data to view via the ViewData dictionary

• Directly, e.g. ViewData[“key”] = obj;

• View model object, e.g. ViewData.Model = obj

Page 30: ASP.NET MVC 2.0

ViewData Dictionary

Page 31: ASP.NET MVC 2.0

Model Object

Page 32: ASP.NET MVC 2.0

The Familiar Web Forms View

• You can reuse most of your ASP.NET Web Form

knowledge, for examples:

• Directives & syntax

• Localization

• Master page

• (MVC) user control

• Things you shouldn‟t use:

• Server control (unless reusing)

• Code-behind & Web Forms life-cycle

• Things you couldn‟t use:

• View state

• Post back

Page 33: ASP.NET MVC 2.0

Dynamic Code Options

Technique Description

Inline code The same old <% … %> and <%= … %>

HTML Helpers Built-in or extension methods for HtmlHelper class,

e.g. Html.TextBox(…), Html.BeginForm(…) etc.

Partial views Render MVC user controls, which can be reused in

many places, e.g. Html.RenderPartial(“Task”)

Partial action Invoke an MVC action and execute returned action

result, e.g. Html.RenderAction("ShowTagCloud",

"BlogEntry")

Server controls Using standard ASPX control registration & using

syntax

Page 34: ASP.NET MVC 2.0

Common HtmlHelper Methods

• For each of the above, there‟s a corresponding

Html.XxxFor(…) method that works with expression tree

Method Corresponding HTML

Html.CheckBox(…) <input id=“…" name=“…" type="checkbox" value=“…"

…/>

Html.TextBox(…) <input id=“…" name=“…" type="text" value=“…" …/>

Html.TextArea(…) <textarea id=“…" name=“…" …>…</textarea>

Html.Password(…) <input id=“…" name=“…" type=“…" value=“…" …/>

Html.RadioButton(…) <input checked=“…" id=“…" name=“…"

type=“…" value=“…" …/>

Html.Hidden(…) <input id=“…" name=“…" type=“…" value=“…" …/>

Html.BeginForm(...) <form id=“…” …>…</form>

Page 35: ASP.NET MVC 2.0

Custom HtmlHelper Methods

Page 36: ASP.NET MVC 2.0

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

Page 37: ASP.NET MVC 2.0

ACTION METHOD SELECTORS

Page 38: ASP.NET MVC 2.0

Action Method Selectors

• Attributes used in Controller#Execute() to know

which action to invoke

• Built-in selectors

• AcceptVerbs(HttpVerbs)

• Or more convenient versions: HttpGet & HttpPost

• Inherit ActionMethodSelectorAttribute

• Override bool IsValidForRequest(…)

Page 39: ASP.NET MVC 2.0

FILTERS

Page 40: ASP.NET MVC 2.0

Filters

• .NET attributes adding logic

• Before & after action method invocation

• Before & after action result invocation

• During unhandled exception

• During request authorization

• Filters can be applied to

• Individual action

• All actions in a controller

• Built-in filters: OutputCacheAttribute, AuthorizeAttribute, ValidateInputAttribute,

ValidateAntiForgeryTokenAttribute, HandleErrorAttribute, ChildActionOnly

Page 41: ASP.NET MVC 2.0

Types of Filter

Filter Type Interface Methods to Override

Authorization filter IAuthorizationFilter OnAuthorization()

Action filter IActionFilter OnActionExecuting(),

OnActionExecuted()

Result filter IResultFilter OnResultExecuting(),

OnResultExecuted()

Exception filter IExceptionFilter OnException()

Page 42: ASP.NET MVC 2.0

MODEL VALIDATION

Page 43: ASP.NET MVC 2.0

Business Rule Validation

• Business rules needs enforcing

• User name must be supplied

• Email format must be correct

• It‟s also desirable to enforce rules at both server-

side and client-side

• DRY principle must be followed for maintainability

Page 44: ASP.NET MVC 2.0

ASP.NET MVC Model Validation

• Apply one or more validation attributes to the

model classes and/or their properties

• The model binding process validates and populates ModelState.Errors collection

• Check result with ModelState.IsValid or ModelState.IsValidField(propertyName)

• More error can be added after model binding • ModelState.AddModelError(key, message);

• key: use string.Empty for non-property error

Page 45: ASP.NET MVC 2.0

DataAnnotations Validation Attributes

Attribute Description

Range Validates whether the property value falls in a min-max

range

RegularExpression Validates the property against a specified regular expression

Required Validates whether the property value is provided

StringLength Validates the maximum length of a property value

Validation The base class for all validation attributes, including custom

attributes

Page 46: ASP.NET MVC 2.0

Model Validation in Views

• Html Helper Methods • Html.ValidationSummary(

bool excludePropertyErrors, string message)

• Html. ValidationMessage(

string modelName)

• Html. ValidationMessageFor(

Expression<Func<TModel, TProperty>> expression)

• Html.EnableClientValidation()

• References to JavaScript files • ~/scripts/jquery-1.3.2.min.js

• ~/scripts/jquery.validate.min.js

• ~/scripts/MicrosoftMvcJQueryValidation.js

Page 47: ASP.NET MVC 2.0

MODEL TEMPLATES

Page 48: ASP.NET MVC 2.0

Model Templates

• Developers describe rendering rules using

metadata

• ASP.NET MVC renders based on metadata using

built-in or custom templates

Page 49: ASP.NET MVC 2.0

DataAnnotations UI Attributes

Attribute Description

DisplayName Used in Html.Label()/LabelFor() to generate the label text

HiddenInput Generates a hidden input for the property

DataType Indicates the data type of the property (e.g. Email, Password)

ScaffoldColumn Indicates whether the property should be shown or ignored

DisplayFormat Adds formatting rules to the property (e.g. DataFormatString,

NullDisplayText etc.)

ReadOnly Indicates that users shouldn‟t be able to modify the property

UIHint Specifies a template to use

Page 50: ASP.NET MVC 2.0

Model Templates in Views

• Display

• Html.Display(“PropertyName”)

• Html.DisplayFor(model => model.PropertyName)

• Html.DisplayForModel()

• Editor

• Html.Editor(“PropertyName”)

• Html.EditorFor(model => model.PropertyName)

• Html.EditorForModel()

Page 51: ASP.NET MVC 2.0

AND BEYOND…

Page 52: ASP.NET MVC 2.0

And Beyond…

ASP.NET MVC 2

• Areas

• Asynchronous controller

ASP.NET MVC 3 Beta

• Razor view engine

• NuPack

• Global filters

• JSON model binding

• Better DI support

• …

Page 53: ASP.NET MVC 2.0

THANK YOU!

[email protected]

http://vn.linkedin.com/in/buunguyen

www.twitter.com/buunguyen