SlideShare a Scribd company logo
1 of 53
Download to read offline
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
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

What's hot

[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JSIvano Malavolta
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Marakana Inc.
 
CNIT 129S: 11: Attacking Application Logic
CNIT 129S: 11: Attacking Application LogicCNIT 129S: 11: Attacking Application Logic
CNIT 129S: 11: Attacking Application LogicSam Bowne
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldMarakana Inc.
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneVincent Hoogendoorn
 
How to get full power from WebApi
How to get full power from WebApiHow to get full power from WebApi
How to get full power from WebApiRaffaele Rialdi
 
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldMarakana Inc.
 
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)Sam Bowne
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVCEmad Alashi
 
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)Sam Bowne
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsEffie Arditi
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
ASP.NET MVC 4 - Routing Internals
ASP.NET MVC 4 - Routing InternalsASP.NET MVC 4 - Routing Internals
ASP.NET MVC 4 - Routing InternalsLukasz Lysik
 
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making our VIPER more reactiveInfinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making our VIPER more reactiveInfinum
 
Breaking the limits_of_page_objects
Breaking the limits_of_page_objectsBreaking the limits_of_page_objects
Breaking the limits_of_page_objectsRobert Bossek
 

What's hot (20)

[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6
 
CNIT 129S: 11: Attacking Application Logic
CNIT 129S: 11: Attacking Application LogicCNIT 129S: 11: Attacking Application Logic
CNIT 129S: 11: Attacking Application Logic
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows Phone
 
How to get full power from WebApi
How to get full power from WebApiHow to get full power from WebApi
How to get full power from WebApi
 
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
CNIT 129S: 12: Attacking Users: Cross-Site Scripting (Part 2 of 3)
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi Applications
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
ASP.NET MVC 4 - Routing Internals
ASP.NET MVC 4 - Routing InternalsASP.NET MVC 4 - Routing Internals
ASP.NET MVC 4 - Routing Internals
 
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making our VIPER more reactiveInfinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making our VIPER more reactive
 
Breaking the limits_of_page_objects
Breaking the limits_of_page_objectsBreaking the limits_of_page_objects
Breaking the limits_of_page_objects
 

Similar to ASP.NET MVC 2.0

ASP.NET MVC_Routing_Authentication_Aurhorization.pdf
ASP.NET MVC_Routing_Authentication_Aurhorization.pdfASP.NET MVC_Routing_Authentication_Aurhorization.pdf
ASP.NET MVC_Routing_Authentication_Aurhorization.pdfsetit72024
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Thomas Robbins
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015Hossein Zahed
 
Asp.net mvc 6 with sql server 2014
Asp.net mvc 6 with sql server 2014Asp.net mvc 6 with sql server 2014
Asp.net mvc 6 with sql server 2014Fahim Faysal Kabir
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8Thomas Robbins
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantNitin Sawant
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
Azure Application insights - An Introduction
Azure Application insights - An IntroductionAzure Application insights - An Introduction
Azure Application insights - An IntroductionMatthias Güntert
 
4. Introduction to ASP.NET MVC - Part I
4. Introduction to ASP.NET MVC - Part I4. Introduction to ASP.NET MVC - Part I
4. Introduction to ASP.NET MVC - Part IRohit Rao
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Joe Wilson
 

Similar to ASP.NET MVC 2.0 (20)

ASP.NET MVC_Routing_Authentication_Aurhorization.pdf
ASP.NET MVC_Routing_Authentication_Aurhorization.pdfASP.NET MVC_Routing_Authentication_Aurhorization.pdf
ASP.NET MVC_Routing_Authentication_Aurhorization.pdf
 
Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
Asp.net mvc 6 with sql server 2014
Asp.net mvc 6 with sql server 2014Asp.net mvc 6 with sql server 2014
Asp.net mvc 6 with sql server 2014
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
ASP.NET MVC 3
ASP.NET MVC 3ASP.NET MVC 3
ASP.NET MVC 3
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
Azure Application insights - An Introduction
Azure Application insights - An IntroductionAzure Application insights - An Introduction
Azure Application insights - An Introduction
 
4. Introduction to ASP.NET MVC - Part I
4. Introduction to ASP.NET MVC - Part I4. Introduction to ASP.NET MVC - Part I
4. Introduction to ASP.NET MVC - Part I
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 

More from Buu Nguyen

On Becoming a Technical Lead
On Becoming a Technical LeadOn Becoming a Technical Lead
On Becoming a Technical LeadBuu Nguyen
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0Buu Nguyen
 
Stories about KMS Technology
Stories about KMS TechnologyStories about KMS Technology
Stories about KMS TechnologyBuu Nguyen
 
Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Buu Nguyen
 
Building Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuilding Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuu Nguyen
 
New Features of ASP.NET 4.0
New Features of ASP.NET 4.0New Features of ASP.NET 4.0
New Features of ASP.NET 4.0Buu Nguyen
 
C# 4.0 and .NET 4.0
C# 4.0 and .NET 4.0C# 4.0 and .NET 4.0
C# 4.0 and .NET 4.0Buu Nguyen
 

More from Buu Nguyen (10)

On Becoming a Technical Lead
On Becoming a Technical LeadOn Becoming a Technical Lead
On Becoming a Technical Lead
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0
 
Stories about KMS Technology
Stories about KMS TechnologyStories about KMS Technology
Stories about KMS Technology
 
HTML5 in IE9
HTML5 in IE9HTML5 in IE9
HTML5 in IE9
 
Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0
 
Building Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuilding Scalable .NET Web Applications
Building Scalable .NET Web Applications
 
New Features of ASP.NET 4.0
New Features of ASP.NET 4.0New Features of ASP.NET 4.0
New Features of ASP.NET 4.0
 
C# 4.0 and .NET 4.0
C# 4.0 and .NET 4.0C# 4.0 and .NET 4.0
C# 4.0 and .NET 4.0
 
Combres
CombresCombres
Combres
 
Fasterflect
FasterflectFasterflect
Fasterflect
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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
  • 8.
  • 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 • …