ASP.NET MVC 2.0

Post on 01-Nov-2014

7020 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Training slides for Microsoft customers

Transcript

ASP.NET MVC 2.0

10/29/2010

Buu Nguyen

• Microsoft MVP, MCSD.NET, SCJD, SCBCD

• Vice President of Technology, KMS Technology

• Lecturer, RMIT University Vietnam

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…

ASP.NET MVC BASICS

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

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

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

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

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

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

Let’s see the completed TodoApp

ROUTING

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

Incoming URL to Route Info

actual value becomes

TaskController.cs

Route Constraints

• Strings (regular expression)

• Classes implementing IRouteConstraint E.g. HttpMethodConstraint

Custom constraints

Outgoing URLs & Links • Generate outgoing URL from route info

• UrlHelper#Action(…)

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

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

CONTROLLERS & ACTION METHODS

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)

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

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.

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

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

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

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

VIEW RESULTS & VIEWS

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

ViewData

• Controllers pass data to view via the ViewData dictionary

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

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

ViewData Dictionary

Model Object

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

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

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>

Custom HtmlHelper Methods

MvcHandler

Action

Result

Controller

Factory

Action

View

Engine

View

View

Result

Controller forwards

invokes

produces produces

defin

es

Model

Route

maps

ACTION METHOD SELECTORS

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(…)

FILTERS

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

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

MODEL VALIDATION

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

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

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

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

MODEL TEMPLATES

Model Templates

• Developers describe rendering rules using

metadata

• ASP.NET MVC renders based on metadata using

built-in or custom templates

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

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

AND BEYOND…

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

• …

THANK YOU!

buunguyen@kms-technology.com

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

www.twitter.com/buunguyen

top related