ASP.NET MVC for Dummies

potpiedicedInternet and Web Development

Jul 5, 2012 (5 years and 13 days ago)

1,474 views

ASPNETMVCforDummies
ASP
.
NET

MVC

for

Dummies
Paul Litwin
Deep Training &
Fred Hutchinson Cancer Research Center
p
aul
@
dee
p
trainin
g
.com
p@pg
blog.paullitwin.com
twitter.com/plitwin
Paul Litwin
•Developer

Focus: ASP.NET, ASP, C#, SQL Server, Reporting Services

䵃卄

䵃卄

Microsoft MVP

Programmer Manger with
Fred Hutchinson Cancer Research Center (Seattle)
•Co-Founder and Senior Trainer

Deep Training
•www.deeptraining.com
CfChi/Sk

C
on
f
erence
Ch
a
i
r
/S
pea
k
er

Chair, Microsoft ASP.NET Connections

Member INETA Speakers Bureau

Authorofoveradozenbooks&coursesincluding

Author

of

over

a

dozen

books

&

courses
,
including

•AppDevSQL Server 2005 & 2008 Reporting Services Courses
•ASP.NET for Developers
•Access Cookbook
•Access 2002 Desktop/Enterprise Dev Handbook
UpdatedSlides&SamplesDownload
Updated

Slides

&

Samples

Download

Youcandownloadthemfrom:
You

can

download

them

from:

www.deeptraining.com/litwin
ASP.NETMVCforDummiesAgenda
ASP.NET

MVC

for

Dummies

Agenda
•What?

What is ASP.NET MVC?
•Why?

Why can’t I just use Web Forms?

Why use ASP.NET MVC?
•How?

How does it work?

Show me how to build an app using it
ASPNETMVC
ASP
.
NET

MVC
What?
ASP.NETMVC
ASP.NET

MVC

Anewwaytobuildhighly
-
testableappson
A

new

way

to

build

highly
testable

apps

on

top of the ASP.NET Framework

AnalternativetousingRADWebForms

An

alternative

to

using

RAD

Web

Forms
MVCDesignPattern
MVC

Design

Pattern
•Conery, Hanselman, Haack, Guthrie define it
as…

An architectural pattern used to separate an
applicationintothreemainaspects
application

into

three

main

aspects
•Model.Set of classes that represent data and business rules
for how data can be changed and manipulated

V
iew. Application’s user interface
•Controller.Set of classes that handles communication from
user, overall application flow, and application-specific logic
ASP.NETMVC
ASP.NET

MVC
•ASP.NET MVC 1.0

Requires ASP.NET 3.5 / Visual Studio 2008 SP1

Download Microsoft ASP.NET MVC 1.0 from
http://aspnet/mvc
http://asp
.
net/mvc
•ASP.NET MVC 2.0

偡牴潦噩獵慬却畤楯㈰㄰

偡牴



噩獵慬

却畤楯

㈰㄰
•N潴桩湧⁴漠摯睮汯慤d楦⁵獩湧⁷楴栠噓′〱i
•W桡琠睥h睩汬w畳攠瑨楳⁳敳獩潮

Can also be used with Visual Studio 2008
•Download from http://asp.net/mvc
ASPNETMVC
ASP
.
NET

MVC
Why?
WhySeparateConcerns?
Why

Separate

Concerns?

Makesyourappcodemore
Makes

your

app

code

more


testable
modifable/refactorable

modifable

/

refactorable

reusable
maintainable

maintainable
?”scalable
What

sWrongwithWebForms?
Whats

Wrong

with

Web

Forms?
•Nothin
g
…but…
g

Web forms don’t allow as precise control over
“separation of concerns”

High level of abstraction
•Not as “close to the metal” as some devswant

Web forms are difficult to test

Search engine optimization (SEO) issues
•ASP.NET 4.0 addresses this somewhat
What Web Forms & MVC
HiC
H
ave
i
n
C
ommon
•Both hosted in Visual Studio
•Both built on ASP.NET
•Both run on IIS
•Both use .aspxpages

Both can use Master pages

瑨潵杨祯yc慮畳uad楦晥牥湴癩敷敮杩湥楦祯y
’
d汩步inM噃

瑨潵杨

祯y

捡c

畳u

a

摩晦敲敮d

癩敷

敮杩湥



祯yd

汩步



䵖M

⡎䡡浬Ⱐ印慲欬(䉲慩氬⁎噥汯B楴礬⁥瑣⸩
•B潴栠捡渠畳攠慮礠摡瑡⁡捣敳猠晲慭敷潲欠⡁䑏⹎䕔Ⱐ
䱉乑Et楴Fkt)
䱉乑

E
n
瑩t

F
牡浥睯r
k
Ⱐ,
t

)
ASPNETMVC
ASP
.
NET

MVC
How?
BasicTenetsofASP.NETMVC
Basic

Tenets

of

ASP.NET

MVC
•Convention over confi
g
uration
g
•Don’t repeat yourself (DRY)

Pluggability
wheneverpossible

Pluggability
whenever

possible

We will use in-the-box parts of ASP.NET MVC
butalmosteverything(dataaccesstesting
but

almost

everything

(data

access
,
testing

framework, view engine, validation, etc. can
be re
p
laced
)
p)
•Try to be helpful, but get out
ofthedeveloper

sway
of

the

developers

way
Model,View,Controller
Model,

View,

Controller

Model
Model

Data and business rules
View

View

Application’s UI. Will employ a view for each
pagethatisdisplayedtousers
page

that

is

displayed

to

users
•Controller

Classes that are responsible for application
workflow and logic
BesidestheM,theV,andtheC…
Besides

the

M,

the

V,

and

the

C…
•Routing
NiceURLsarepossiblebecauseofroutingengine

Nice

URLs

are

possible

because

of

routing

engine

Routes are stored in global.asax
•Binding to data

䑥晡畬D
䵯摥求楮摥M
慵瑯
浡杩捡汬m捯湶敲瑳景牭癡汵敳慮a

䑥晡畬D

䵯摥求楮摥M
慵瑯
-
浡杩捡汬m

捯湶敲瑳

景牭

癡汵敳

慮a

牯畴攠摡瑡⁩湴漠摡瑡

Allows you to strongly type your pages & controller methods
•Scaffoldin
g
Views
g

ASP.NET MVC will automatically provide scaffolding to help you
create your views

Helpful, but almost always will want to modify views it creates
•Html Helpers

Methods you can use in views to generate
Html elements, usually bound to data
BuildinganMVCApplication
Building

an

MVC

Application

Remainderoftalkwillfocusonbuildingan
Remainder

of

talk

will

focus

on

building

an

end-to-end MVC application that can be
usedtodisplayandeditproductrecords
used

to

display

and

edit

product

records

from the Northwind database
BuildinganMVCApplication
Building

an

MVC

Application

Demo1

MVCApp
Demo

1

MVC

App

Create ASP.NET MVC Application
GoaheadandletVScreatetestapp

Go

ahead

and

let

VS

create

test

app

Remove following starter files

Controllers|HomeControllercs

Controllers|HomeController
.
cs
•All views in Views|Homefolder

InTestapp,
Controllers|HomeControllerTest.cs
In

Test

app,

Controllers|HomeControllerTest.cs
ASP.NETMVCProjectAnatomy
ASP.NET

MVC

Project

Anatomy

Content
Content
•Controllers
Mdl

M
o
d
e
l
s
•Scripts
•Views

Shared
Shared
•Global.asax
BuildingModels
Building

Models

ModelisthepartoftheMVCappthat
Model

is

the

part

of

the

MVC

app

that

provides data access

奯Yc慮扵楬b浯摥m畳楮u

奯Y

捡c

扵楬b

浯摥m

畳楮u
•A䑏⹎䕔
•
䱉乑瑯卑S
䱉乑



卑S
•E湴敲灲楳攠汩扲慲n
•N桩扥牮慴h

BuildinganMVCApplication
Building

an

MVC

Application

Demo2

CreatingBasicModel
Demo

2

Creating

Basic

Model

We will use LINQ to SQL
Wewillbuildamodelon3tablesfrom

We

will

build

a

model

on

3

tables

from

Northwind

Products
Products
•Categories
•Suppliers

Set UpdateCheckproperty on
Product fields to Never
BuildinganMVCApplication
Building

an

MVC

Application

Demo3

AddingRepositoriestoModel
Demo

3

Adding

Repositories

to

Model

While we could have controller call LINQ to
SQLclassesdirectlyit

sbettertoprovide
SQL

classes
,
directly
,
its

better

to

provide

another layer using a repositorypattern

Wewillcreaterepositoryclassesforeach
We

will

create

repository

classes

for

each

model object
•Very similar to creating a business tier in N-tier app
design
BuildinganMVCApplication
Building

an

MVC

Application

Demo4

ModifyingRoutingTable
Demo

4

Modifying

Routing

Table

Global.asax

Defaultrouteassumesidistheprimarykey

Default

route

assumes

id

is

the

primary

key
•Need to change to use ProductIDfor
HomeController
CreatingControllers
Creating

Controllers

Theintelligenceofyourapplication
The

intelligence

of

your

application

Ferries data back & forth to model
Methodsthateventuallycallviews

Methods

that

eventually

call

views

Add Controller dialog can scaffold CRUD
methodsforyou
methods

for

you
BuildinganMVCApplication
Building

an

MVC

Application

Demo5

CreatingHomeController
Demo

5

Creating

Home

Controller

Create HomeControllerwhich will…

BeresponsibleforCRUDoperationsforProducts

Be

responsible

for

CRUD

operations

for

Products
•Replace form collection in post methods for
(Create, Edit, Delete) with strongly-typed Product
objects
ConstructingViews
Constructing

Views

Defaultviewengineisthe
aspx
page
Default

view

engine

is

the

aspx
page
•The UI of the application
BuildinganMVCApplication
Building

an

MVC

Application
•Demo 6

Creatin
g
Views
g

Scaffold our views by right-clicking on each of the
HomeControllermethods and selecting Add View
Ut
tdi
PdtAMdlPdt

U
se s
t
rong-
t
ype
d
v
i
ew
P
ro
d
uc
t
s
A
pp.
M
o
d
e
l
s.
P
ro
d
uc
t

Need to modify Index view since generated hyperlinks
use id instead of ProductID

Also, need to fix up Create and Edit views
•Remove ProductIDfrom Create
•Don’t allow editing of ProductIDin Edit
•Replace Discontinued textbox with
checkbox in Create & Edit
BuildinganMVCApplication
Building

an

MVC

Application
•Demo 7

A
ddin
g
Dro
p
down Su
pp
ort
gppp

Add ProductFormModelclass to HomeController

Change Edit/Create methods to pass ProductFormModelto
views
views

Change type of Edit and Create views to derive from
ProductFormModelclass
Replaceeachinstanceof

model

with

modelProduct


Replace

each

instance

of

model
.
with

model
.
Product
.

Add ProductIDHtml.HiddenForon Edit page

Replace category and supplier Html.TextBoxForhelpers with
HtlDDLitF
hl
Ht
m
l
.
D
rop
D
own
Li
s
tF
o
r
h
e
l
pers
BuildinganMVCApplication
Building

an

MVC

Application
•Demo 8

A
ddin
g
Validation
g

Add “Buddy” partial class for Products with
data annotations

Add if (!ModelState.IsValid)to Create and
Edit post methods

Adding client-side support requires a couple
of additional steps
•See http://haacked.com/archive/2009/11/19/aspnetmvc2-
custom-validation.aspx
RefactoringApptoSupportTesting
Refactoring

App

to

Support

Testing
•Currentl
y,
controller and model are ti
g
htl
y

y,gy
coupled; Can’t test app without database
dependency
•Can be fixed by using dependency injection

Extract interface

Update controller to support Constructor Injection

Create fake repository that also derives from interface
BuildinganMVCApplication
Building

an

MVC

Application
•Demo 9 –Refactoring for Testing

Right-click on ProductRepositoryclass and select
Refactor|ExtractInterface
Makeinterfacepublic

Make

interface

public

Modify HomeControllerwith two constructors
•Parameterlessthat creates new ProductRe
p
ositor
y
py
•Parameterized that allows passing in IProductRepository

Add FakeProductRepositoryclass
•: IProductRepository
•Right-click on interface and select
Implement Interface
ConstructingTests
Constructing

Tests

Foreachunittest
For

each

unit

test

Arrange

Arrangetestsettingupanypre
-
requisites

Arrange

test
,
setting

up

any

pre
-
requisites

Act

Acttotestfeatureofapplication
Act

to

test

feature

of

application

Assert

Assertwhatyouexpect
Assert

what

you

expect
BuildinganMVCApplication
Building

an

MVC

Application
•Demo 10

Creatin
g
& Runnin
g
Unit Test
gg

In Test project, right-click on Controllers, and
select Add New Testand select Unit Test

Create CreateTestProductsmethod

Create tests usin
g
FakeProductRe
p
ositor
y
g
py

To run tests, right-click on
HomeControllerTestclass name and select
Run Tests
Summary
Summary

HowdoesMVCcomparetoWebForms
How

does

MVC

compare

to

Web

Forms

development?
ASP.NETMVCPluses(Why)
ASP.NET

MVC

Pluses

(Why)

Anewwaytobuildhighly
-
testableappson
A

new

way

to

build

highly
testable

apps

on

top of the ASP.NET Framework

Nopost
-
backs
No

post
-
backs
•Requests map to methods rather than pages
SEO
fidlURL

SEO
-
f
r
i
en
dl
y
URL
s
•Supports TDD and Unit Tests
•Encourages use of design patterns and best
practices
ASP.NETMVCMinuses(WhyNot)
ASP.NET

MVC

Minuses

(Why

Not)

NotasRADasusingWebForms
Not

as

RAD

as

using

Web

Forms
•No drag and drop experience
D’tbildlliith

D
oesn
’t

b
u
ild
on a
ll
your exper
i
ence w
ith

ASP.NET server controls
•Encourages use of design patterns and
best practices
HowDoIDecideWhichtoUse?
How

Do

I

Decide

Which

to

Use?

ChooseMVCifyou…
Choose

MVC

if

you…

want to embrace design patterns and are willing to
put hard work into understanding them

are disciplined and want to follow design patterns and
best practices
areinterestedinembracingunittests

are

interested

in

embracing

unit

tests

are interested in embracing TDD

慲a扥楮b瑯汤瑯畳uitbyy潵o敭灬潹敲⽣汩敮e

慲a

扥楮b

瑯汤



畳u





祯畲

敭灬潹敲⽣汩敮e
HowDoIDecideWhichtoUse?
How

Do

I

Decide

Which

to

Use?

ChooseWebFormsifyou…
Choose

Web

Forms

if

you…

you like Web Forms

y
our brain hurts when readin
g
about desi
g
n
p
atterns
yggp

you don’t like following patterns or best pratices

are not interested in embracing unit tests or TDD

are being told to use it by your employer/client
AnotherWaytoLookAtIt…
Another

Way

to

Look

At

It…

Buildinganintranetsitewithlotsofdata
Building

an

intranet

site

with

lots

of

data

editing

坥WF潲浳浡mbe扥瑴敲s畩瑥u

坥W

䙯牭F

浡m



扥瑴敲

獵楴敤
•B畩汤楮朠慮⁉湴敲湥琠獩瑥⁷桥牥⁈呍䰬u
灥牦潲浡湣p慮a獣慬慢楬楴sa牥
灥牦潲浡湣p

慮a

獣慬慢楬楴s

慲a

灡牡浯畮p
䅓A久NM噃bb瑴楴d

ASP
.
NET

MVC
may
b
e
b
e
tt
er su
it
e
d
SomethingtoConsider…
Something

to

Consider…
•Once
y
ou start on MVC
p
ath
,

y
ou will find
y
ou will
yp,yy
find yourself getting pulled in deeper and deeper…

How do I write good unit tests with good coverage?
DdifftVii?

D
o you use a
diff
eren
t

Vi
ew eng
i
ne
?

Do you use a unit test framework

Doyouuseamockframework?
Do

you

use

a

mock

framework?

What about validation framework?

What about dependency injection, inversion of
tl?
con
t
ro
l?


WhatAboutMe?
What

About

Me?

IamintriguedwithASP.NETMVC
I

am

intrigued

with

ASP.NET

MVC
•However…
Mybraindoeshurtwhenreadingabout

My

brain

does

hurt

when

reading

about

design patterns

Il潶oW敢䙯牭F

I

汯癥

坥W

䙯牭F
•佔佈O
I汩l瑨楤fitt瑩iti扩汩b

I

lik
e
th
e
id
ea o
f
un
it

t
es
ti
ng, ma
i
n
t
a
i
na
bilit
y,
and best practices
LearningResources
Learning

Resources
•Bin
g
/Goo
g
le for Nerd Dinner MVC
gg

Chapter by Scott Guthrie
•ASP.NET MVC Framework Unleashed

Walthe
r
•Professional ASP.NET MVC 1.0

䍯湥特
䡡湳敬浡HH慡捫G畴桲楥

䍯湥特

䡡湳敬浡H

䡡慣H

䝵瑨物G
•䅓倮久吠楮A䅣瑩潮

P
a
l
e
rm
o,

Sc
h
e
irm
a
n
,
B
oga
r
d
aeo,Scea,
ogad
•Head First Design Patterns

Freeman & Freeman
Thank You!
•Please complete evaluation forms
•Contact: paul@deeptraining.com
•Download u
p
dated slides & sam
p
les from
pp
●www.deeptraining.com/litwin
YourFeedbackisImportant
Your

Feedback

is

Important
Please fill out a session evaluation form
dropitoffattheconferenceregistration
drop

it

off

at

the

conference

registration

desk.
Thank you!