ASP.NET MVC
Training – Part 1
AN ASP.NET MVC INTRODUCTION
Lee Englestone (@LeeEnglestone)
Tech Lead @ Kitbag.com
www.ManchesterDeveloper.com
Overview
This primer covers Microsofts implementation of
the MVC pattern the ASP.NET MVC Framework
Examples shown in C# but we use VB.NET and
there are some slight differences
Part 1
MVC Pattern, Models, Views, Controllers, Actions,
Routing, ActionFilters, Razor, Layout Views,
Capturng Input
Part 2
HtmlHelpers, PartialViews, Areas, Bundling,
Minification, Scaffolding, TDD/Unit Testing,
Dependency Injection, Bootstrap, Custom mobile
views, ModelAttributes, ModelState, AsyncController
ASP.NET MVC v WebForms
WebForms
Maintain states with
VIewState, Postbacks and
Page Events
One big form on each page
Less control over rendered
HTML
MVC
Does not automatically
maintain state between
requests. Uses HTTP GET and
POST
Can have multiple forms on
a page
More control over rendered
HTML
TDD a lot easier
Seperation of Concerns
Note : MVC does not replace WebForms. WebForms are not evil and they
can also be used with best practices. But it’s easier to see the benefits of
using MVC (In my opinion) especially in Greenfield development
Url Structure
Uses Url Routing (not to be confused with re-writing)
Completely configurable
By default
http://www.site.com/{Controller}/{Action}/{Id}
For example /Product/View/Adidas-bag
If using ‘Areas’ then..
http://www.site.com/{Area}/{Controller}/{Action}/{Id}
Routing
Routes kept in RouteTable
Defined by default in
App_Start/RouteConfig.cs
Routes urls in an
expected format to an
Action on Controller
Can have restrictions..
i.e. Id must be integer or
2 characters long
The default route (if none provided is Home/Index)
Controllers
The entry point of http / page
requests
Mapped to by Routing
Contain ‘Action’ methods
For example returning views,
content, redirects
Inherit from
System.Web.Mvc.Controller
class
AsyncController also exists
(Discussed in Part 2)
Actions
Methods on Controllers
If no action is present in url, then the Index method is called (if exists)
so /home would execute Index Action on HomeController
These are just
returning empty
views at the moment
By default it will a
return a view with the
same name as the
Action
ViewBags are
dynamic objects..
ViewBags
Are dynamic objects
They circumvent strongly typing model properties
in views so use sparingly and only if necessary
We don’t use ViewBags
It’s a much better practice to instantiate a
‘Model’ with populated data and pass into the
view
ActionResult Types
EmptyResult
ContentResult*
JsonResult*
RedirectResult*
RedirectToRouteResult
ViewResult*
PartialViewResult*
FileResult
FilePathResult
FileContentResult
FileStreamResult
JavaScriptResult
*The main ones you’ll use
The Following things can be returned from Actions
Exercise : Run Application
Hit F5
Note: This is /Home/Index
i.e Home Controller, Index
Action
This design is the
Bootstrap css framework
(Discussed in Part 2)
Models
Models are usually simple classes with
a number or properties which will be
used in the Views
Properties can be decorated with
different attributes to provide
additional functionality (Covered in
Part 2)
Views
Views are returned from Controllers
Before the View is returned a Model can be
bound to it
They can access Properties on the Views Model in
in a type safe manner
Type of Model, the View uses
Binding to Properties on the Model
General code can be ran in
‘server’ blocks
Exercise : Create
HomeViewModel Model
Create a new file/class in /Models called
HomeViewModel.cs
Add a DateTime property on the class called Now
Add a string property on the class called Message
Exercise : Bind HomeViewModel to
Index View
In the Index Action on the HomeController..
Instantiate a new HomeViewModel object
Set Now property to DateTime.Now
Give Message some text
Return the Model in the View() result
Exercise : Update Home/Index
View to use HomeViewModel
Open /Views/Home/Index.cshtml
Add a @model declaration at the top to use your new
HomeViewModel
Bind the Message property and the Now property to
somewhere on the page using the Razor syntax
Press F5, refreshing page will hit controller and update time
each time
Razor View Syntax
Razor is a markup syntax
Uses @
Used in .cshtml & .vbhtml files
Slightly similar to WebForms <% %>
Code block & variable assignment
Using variable from earlier code
block
Iterating over collection
Conditional clauses
Layout Views
Similar to WebForms .Master pages
Provides common html for pages to share
Provides area for page specific content
Default located at ViewsShared_Layout.cshtml
Default Layout View
HtmlHelpers that create
Hyperlinks (Discussed in Part 2)
Where main body of Views will appear
Partial View (Discussed in Part 2)
Script Bundle (Discussed in Part 2)
Style Bundle (Discussed in Part 2)
Action Filters
Can run code before / after an action is called
Commonly used ‘out of the box’ ActionFilters
[OutputCache(Duration=“60”)]
Caches and returns the previous result of the Action
for the declared duration. Can VaryByParam etc
[Authorize]
Only allow action to be executed if current user is
authenticated
(HttpContext.Current.User.Identity.IsAuthenticated)
[HttpPost]
Only allow requests HttpPosts to this Action
Exercise : ActionFilters
Add [OutputCache(Duration=60)] to Index
method on HomeController
Run application
Refresh browser and notice Action code is not
being executed subsequent times and the
previous Action result (View) is returned.
Add [Authorize] to the About Action on the
HomeController
Run application
Try to go to About page and notice you’ll be
redirected to login page
Capturing Input with Forms
Html Form “action” must be to a Controller Action
that expects an HttpPost. (Decorated with
[HttpPost])
Name attributes of Inputs on the form need to
match property names on the Views Model
(HtmlHelpers do this automatically, discussed in
Part 2)
Capturing Input with Forms
These 2 are actually the same,
the latter uses HtmlHelpers
These are also the same
(kind of). First = better
Exercise : Capturing Form data
Extend the Model
Add FirstName and LastName string properties to
HomeViewModel class
Extend the View to accept user input
Update Home/Index View to include a form with FirstName and
LastName fields (see previous slide) whose action is Home/Save
Create Thanks Model
Create new Model called Model/ThanksViewModel with
FirstName, LastName properties
Create Thanks View
Create Home/Thanks View, that uses ThanksViewModel and
displays FirstName and LastName on page
Extend HomeController
Add a Save Action that has [HttpPost] attribute, accepts
HomeViewModel and returns a ThanksViewModel to Thanks
View
Next time in Part 2..
HtmlHelpers,
PartialViews,
Areas,
Bundling,
Minification,
Scaffolding,
TDD/Unit Testing,
Dependency Injection,
Bootstrap,
Custom mobile views,
ModelAttributes,
ModelState,
AsyncController