SlideShare a Scribd company logo
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
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
MvcHandler
Action
Result
Controller
Factory
Action
View
Engine
View
View
Result
Controller
forwards
invokes
produces produces
defines
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
defines
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
defines
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
defines
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

More Related Content

PPTX
MVC & SQL_In_1_Hour
PPTX
Asp.Net Mvc
PPTX
Introduction to ASP.Net MVC
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
PDF
CFWheels 2.x and the new CLI (cfcamp 2016)
PDF
Life outside WO
PDF
D2W Stateful Controllers
PPTX
Advance java session 11
MVC & SQL_In_1_Hour
Asp.Net Mvc
Introduction to ASP.Net MVC
2011 NetUG HH: ASP.NET MVC & HTML 5
CFWheels 2.x and the new CLI (cfcamp 2016)
Life outside WO
D2W Stateful Controllers
Advance java session 11

What's hot (20)

PDF
[2015/2016] Require JS and Handlebars JS
PDF
In memory OLAP engine
PDF
Efficient Rails Test-Driven Development - Week 6
PDF
CNIT 129S: 11: Attacking Application Logic
PDF
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
PPTX
MvvmQuickCross for Windows Phone
PPTX
How to get full power from WebApi
PDF
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
PDF
[2015/2016] JavaScript
PDF
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
PDF
KAAccessControl
PDF
[2015/2016] Backbone JS
PPTX
ASP.NET Routing & MVC
PDF
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
PPTX
Real World Asp.Net WebApi Applications
PDF
Web sockets in Angular
PPTX
ASP.NET MVC 4 - Routing Internals
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
PDF
Breaking the limits_of_page_objects
PPTX
Ankor Presentation @ JavaOne San Francisco September 2014
[2015/2016] Require JS and Handlebars JS
In memory OLAP engine
Efficient Rails Test-Driven Development - Week 6
CNIT 129S: 11: Attacking Application Logic
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
MvvmQuickCross for Windows Phone
How to get full power from WebApi
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
[2015/2016] JavaScript
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
KAAccessControl
[2015/2016] Backbone JS
ASP.NET Routing & MVC
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
Real World Asp.Net WebApi Applications
Web sockets in Angular
ASP.NET MVC 4 - Routing Internals
Infinum iOS Talks #4 - Making our VIPER more reactive
Breaking the limits_of_page_objects
Ankor Presentation @ JavaOne San Francisco September 2014
Ad

Similar to ASP.NET MVC 2.0 (20)

PPT
CTTDNUG ASP.NET MVC
PPTX
ASP.MVC Training
PPTX
Asp.net mvc presentation by Nitin Sawant
PPTX
Aspnet mvc
PPTX
Asp.Net MVC Intro
PPTX
Asp.net mvc
PPTX
PPTX
Model view controller (mvc)
PPTX
Asp.net With mvc handson
PPTX
Chapter4.pptx
PPS
Introduction To Mvc
PDF
Asp.Net MVC Framework Design Pattern
PPTX
Head first asp.net mvc 2.0 rtt
PDF
ASP.NET MVC - Whats The Big Deal
PPTX
Hanselman lipton asp_connections_ams304_mvc
PDF
Applying Domain Driven Design on Asp.net MVC – Part 1: Asp.net MVC
PPT
ASP .net MVC
PPTX
Asp.Net MVC 5 in Arabic
PDF
Mvc interview questions – deep dive jinal desai
PPTX
ASP.NET MVC controllers
CTTDNUG ASP.NET MVC
ASP.MVC Training
Asp.net mvc presentation by Nitin Sawant
Aspnet mvc
Asp.Net MVC Intro
Asp.net mvc
Model view controller (mvc)
Asp.net With mvc handson
Chapter4.pptx
Introduction To Mvc
Asp.Net MVC Framework Design Pattern
Head first asp.net mvc 2.0 rtt
ASP.NET MVC - Whats The Big Deal
Hanselman lipton asp_connections_ams304_mvc
Applying Domain Driven Design on Asp.net MVC – Part 1: Asp.net MVC
ASP .net MVC
Asp.Net MVC 5 in Arabic
Mvc interview questions – deep dive jinal desai
ASP.NET MVC controllers
Ad

More from Buu Nguyen (11)

PDF
On Becoming a Technical Lead
PDF
C# 3.0 and 4.0
PDF
Stories about KMS Technology
PDF
ASP.NET MVC 3
PDF
HTML5 in IE9
PDF
Dynamic Binding in C# 4.0
PPTX
Building Scalable .NET Web Applications
PPTX
New Features of ASP.NET 4.0
PPTX
C# 4.0 and .NET 4.0
PPTX
Combres
PPTX
Fasterflect
On Becoming a Technical Lead
C# 3.0 and 4.0
Stories about KMS Technology
ASP.NET MVC 3
HTML5 in IE9
Dynamic Binding in C# 4.0
Building Scalable .NET Web Applications
New Features of ASP.NET 4.0
C# 4.0 and .NET 4.0
Combres
Fasterflect

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
Teaching material agriculture food technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Empathic Computing: Creating Shared Understanding
PDF
cuic standard and advanced reporting.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The AUB Centre for AI in Media Proposal.docx
Teaching material agriculture food technology
Dropbox Q2 2025 Financial Results & Investor Presentation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
Understanding_Digital_Forensics_Presentation.pptx
Review of recent advances in non-invasive hemoglobin estimation
Advanced methodologies resolving dimensionality complications for autism neur...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Empathic Computing: Creating Shared Understanding
cuic standard and advanced reporting.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Digital-Transformation-Roadmap-for-Companies.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

ASP.NET MVC 2.0

  • 2. Buu Nguyen • Microsoft MVP, MCSD.NET, SCJD, SCBCD • Vice President of Technology, KMS Technology • Lecturer, RMIT University Vietnam
  • 3. 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…
  • 5. 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
  • 6. 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
  • 7. 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
  • 9. 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
  • 11. 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
  • 12. Let’s see the completed TodoApp
  • 14. 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
  • 15. Incoming URL to Route Info actual value becomes TaskController.cs
  • 16. Route Constraints • Strings (regular expression) • Classes implementing IRouteConstraint  E.g. HttpMethodConstraint  Custom constraints
  • 17. Outgoing URLs & Links • Generate outgoing URL from route info • UrlHelper#Action(…) • Generate outgoing link from route info • HtmlHelper#ActionLink(…)
  • 20. 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)
  • 21. 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
  • 22. 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.
  • 23. 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
  • 24. 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
  • 25. 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
  • 27. VIEW RESULTS & VIEWS
  • 28. 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
  • 29. ViewData • Controllers pass data to view via the ViewData dictionary • Directly, e.g. ViewData[“key”] = obj; • View model object, e.g. ViewData.Model = obj
  • 32. 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
  • 33. 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
  • 34. 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>
  • 38. 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(…)
  • 40. 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
  • 41. 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()
  • 43. 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
  • 44. 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
  • 45. 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
  • 46. 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
  • 48. Model Templates • Developers describe rendering rules using metadata • ASP.NET MVC renders based on metadata using built-in or custom templates
  • 49. 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
  • 50. 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()
  • 52. 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 • …