ASP.NET MVC in
Download
Report
Transcript ASP.NET MVC in
ASP.NET MVC in Action
Austin Code Camp, 2009
Jeffrey Palermo
Chief Technology Officer
Headspring Systems
•
•
•
•
•
•
•
•
•
ASP.NET MVC History
Getting Started
The Model
Controllers/Actions
Views
Routes
AJAX
MvcContrib
Questions
ASP.NET MVC History
Oct 2007 – Scott Guthrie provides first glimpse
at Alt.Net Conf in Austin, TX
Dec 2007 – First official CTP released
Dec 2007 – MvcContrib open source project
launches
2008 – 4 more CTPs released
Mar 2009 – First version released
Mar 2009 – MvcContrib 1.0 released
Today – Lots of buzz
3
Getting Started - Pattern
4
Getting Started - Components
.Net 3.5 SP1
System.Web.Abstractions.dll
HttpContextBase
HttpRequestBase
etc
System.Web.Routing.dll
ASP.NET MVC v1.0
System.Web.Mvc.dll
Extras
MvcContrib.dll
Microsoft.Web.Mvc.dll
5
Getting Started - Responsibilities
Controllers
Responsible for WHAT a screen does.
Views
Responsible for DISPLAYING the screen.
Models
Responsible for REPRESENTING the task.
6
Getting Started - Advantages
Decouples rendering logic from handling user input
Decouples screen logic from processing the http
request
Leverages interfaces to separate responsibilities within
the presentation layer
Provides complete control over markup rendered
Provides complete control over urls
Different presentation concerns can be independently
tested
7
Getting Started - Web Forms?
ASP.NET
HttpApplication
HttpContext
HttpRequest
HttpResponse
HttpRuntime
HttpUtility
IHttpHandler
IHttpModule
8
WebForms
Server Lifecycle
Postback
ViewState
ASPX
MasterPages
Themes, Skins
General Templating
Getting Started - ASP.NET MVC?
ASP.NET
HttpApplication
HttpContext
HttpRequest
HttpResponse
HttpRuntime
HttpUtility
IHttpHandler
IHttpModule
9
Mvc
Routes
Controllers
ViewData
Filters
MvcContrib
ASPX
MasterPages
Themes, Skins
General Templating
Getting Started – New Project
10
Getting Started – Project Structure
11
Getting Started - Routes
Old
http://codecampserver.com?group=adnug&meetin
g=april09
ASP.NET MVC
http://codecampserver.com/adnug/april09
{ key1}/{ key2 }
Default: {controller}/{action}/{id}
http://foo.com/product/edit/22063748
ProductController.cs
public ViewResult Edit(string id){…}
12
Flow of an ASP.NET MVC Request
Request comes in to /Home
IIS determines the request should be handled
by ASP.NET
ASP.NET gives all HttpModules a chance to
modify the request
The UrlRoutingModule determines that the URL
matches a route configured in the application
13
Flow of an ASP.NET MVC Request
The UrlRoutingModule gets the appropriate
IHttpHandler from the IRouteHandler that is
used in the matching route (most of the time,
MvcRouteHandler)as the handler for the
request
The MvcRouteHandler constructs and returns
MvcHandler.
The MvcHandler, which implements
IHttpHandler executes ProcessRequest.
14
Flow of an ASP.NET MVC Request
The MvcHandler uses IControllerFactory to
obtain an instance of IController using the
"controller" route data from the route
{controller}/{action}/{id}.
The HomeController is found, and its Execute
method is invoked.
The HomeController invokes the Index action.
15
Flow of an ASP.NET MVC Request
The Index action adds some objects to the
ViewData dictionary.
The HomeController invokes the ActionResult
returned from the action, which renders a view.
The “index” view in the views folder displays
the objects in ViewData.
The view, derived from
System.Web.Mvc.ViewPage, executes its
ProcessRequest method.
ASP.NET renders the response to the browser.
16
Model - Long-lived architecture
What causes legacy code?
Dependencies
Coupling
Lack of validated feedback (testing)
18
Model - Layered Architecture
UI
Business Logic
Data Access/Infrastructure
19
Model - Layered Architecture
UI
Business Logic
Data
Access
20
WCF
I/O
Model - Solution Structure
Client
Business Logic
File
Web Service
Infrastructure
Data Access
DB
21
Model - Onion ArchitectureSpeakerController
IConferenceRepository
IUserSession
Domain Services
UserSession
<<class>>
Domain Services
Objects
(aggregates)
Web Service
Application Core/Domain Model
File
ConferenceRepository
<<class>>
22
DB
Model - Solution Structure
UI
Core
IoC Container
Web Service
Infrastructure
DB
23
File
Model - Onion Architecture (flattened)
UI
Data
Access
WCF
I/O
Domain Services
Aggregates (entities)
24
Model - Data-Driven Architecture
More Business Logic
Business Logic
Infrastructure
DB
Web
Service
File
Application Core
25
Controllers – Icontroller
27
Controllers – Action
28
Controllers – Action Requirements
The method must be public.
The method cannot be a static method.
The method cannot be an extension method.
The method cannot be a constructor, getter, or
setter.
The method cannot have open generic types.
The method is not a method of the controller
base class.
The method cannot contain ref or out
parameters.
29
Controllers – Action return types
30
Controllers – ActionResult
31
Controllers – Parameter Binding
32
Controllers – Parameter Binding
public ActionResult Save(string conferenceKey,
string firstName, string lastName, string email,
string webpage)
{
//method body omitted.
}
33
Controllers – Parameter Binding
Precedence
1. Form values
2. Route arguments
3. Querystring parameters
34
Controllers – Parameter Binding
public class AttendeeForm
{
public virtual Guid ConferenceID { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string Webpage { get; set; }
}
//resulting action method signature
public ActionResult Save(AttendeeForm form){}
35
Controllers – Model Binding
36
Controllers – Model Binding
/conference/edit?conference=austincodecamp
37 public ActionResult Edit(Conference conference){…}
Controllers – Registering Binders
38
Controllers – ViewData
39
Controllers – Filters
40
Controllers – Action Filters
IActionFilter – before and after hooks when an
action is executing
IResultFilter – before and after hooks when an
action result is executing
IAuthorizationFilter – hooks when the
controller is authorizing the current user
IExceptionFilter - hooks when an exception
occurs during the execution of a controller
41
Controllers – Provided ActionFilters
System.Web.Mvc.ActionFilterAttribute
System.Web.Mvc.OutputCacheAttribute
System.Web.Mvc.HandleErrorAttribute
System.Web.Mvc.AuthorizeAttribute
System.Web.Mvc.ValidateAntiForgeryTokenAttribute
System.Web.Mvc.ValidateInputAttribute
42
Controllers – Applying Filters
43
Controllers – Action Selectors
System.Web.Mvc.AcceptVerbsAttribute – limits
action selection to requests of the specified
verb type
System.Web.Mvc.NonActionAttribute –
prevents action method from being selected
44
Views – Folder Structure
46
Views – IViewEngine
47
Views – View not found
48
Views – IView
49
Views – WebFormViewEngine
Uses <%=…%> code nuggets
No code-behind
Leverages Master Pages
Partial views can be .aspx or .ascx
Responsibility is rendering markup
50
Views – Helpers
System.Web.Mvc.HtmlHelper<T> - Used to help render
html input elements
Html.TextBox()
Html.CheckBox()
System.Web.Mvc.UrlHelper – Used to render URLS
Url.Action()
Url.Content()
Url.RouteUrl()
System.Web.Mvc.AjaxHelper<T> - Used to render links
and form elements used in an ajax request
Ajax.ActionLink()
Ajax.BeginForm()
51
Views – Strongly Typed
52
Views – Strongly Typed
53
Views – Html Helper Binding
Values will be bound if:
1. The name is found in ModelState
2. The name is found as an explicit key in view data.
3. The name is found as a property of
ViewData.Model.
4. The name is an expression interpretable, such as
Product.Name or Products[2].Name.
54
Views – Validation
55
Views – ModelState Validation
56
Views – Controls
57
Views – Custom View Helper
58
Routes – Overview
60
Routes – Designing Urls
Make simple, clean URLs.
Make hackable URLs.
It is OK for URL parameters to clash.
Keep URLs short.
Avoid exposing database IDs wherever possible.
Consider adding unnecessary information.
61
Routes – Hackable Urls
62
Routes – RESTful
URL
/sessions
/sessions
/sessions/5
/sessions/5
VERB
GET
POST
GET
PUT
/sessions/5
DELETE
/sessions/5/comments GET
63
ACTION
List all sessions
Add a new session
Show session with id 5
Update session with id
5
DELETE session
with id 5
List comments for
session with id 5
Routes – Default
64
Routes – Route Values
65
Routes – Constraints
66
Routes – Testing
"~/austinCodeCamp/attendees/new".ShouldMapTo<AttendeesController>(
x => x.New("austinCodeCamp"));
"~/austinCodeCamp/attendees/123/bob-johnson".ShouldMapTo<AttendeesController>(
x => x.Show("austinCodeCamp", 123));
"~/login".ShouldMapTo<AccountController>(x => x.Login());
67"~/conference/new".ShouldMapTo<ConferenceController>(x => x.New());
Routes – Infinite Flexibility
68
MvcContrib
http://mvccontrib.org
Founded by Eric Hexter and Jeffrey Palermo
Multiple view engines
ViewDataExtensions
IoC Container support
Html helpers
Extra ActionFilters
Anything else the community contributes
70
About me
CTO, Headspring Systems
Agile coach
MCSD.Net
Microsft MVP, ASPInsider
Certified ScrumMaster
Director, Austin .Net User Group
INETA speakers bureau
U.S. Army Veteran
Party with Palermo
www.partywithpalermo.com
Headspring’s Agile Boot Camp
72