INTRO TO
ASP.NET MVC
JAY HARRIS
.NET DEVELOPER
� It is a powerful and elegant means of separating concerns
� There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework . You can implement your own MVC in any platforms. As long as you stick to the following basic idea, you are implementing MVC:
� Model: Real world object that provides data to the View
� View: How to render (UI)
� Controller: Receives end user request and binds model to the view
� It promotes parallel development thanks to the loose coupling between the three main components
� It makes it easier to test application using unit tests
WHAT IS MVC?
ASP.NET MVC
Functionality Three Tiered Architecture MVC Architecture
Look and Feel User Interface View
UI logic User Interface Controller
Business logic/validation Code behind or Model Model
Initial Request User Interface Controller
Accessing Data Data Layer Model/Data Access Layer
MVC VS THREE TIERED ARCHITECTURE
ASP.NET MVC
� Represent a Page as control tree
� Give server-side controls events like their desktop counterparts
� Hides as much HTTP and HTML as is reasonable
� Make state management as transparent as possible
� It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
� It uses a Page Controller pattern that adds functionality to individual pages.
� .NET controls allow for rapid application development.
ADVANTAGES OF WEB FORMS
ASP.NET MVC
� ViewState is powerful, but it has its drawbacks (weight,…)
� Limited control over HTML
� Client IDs and Master Pages� ctl00$ContentPlaceHolder1$UserControl1$TextBox1 enough said…
� Tight coupling of Pages to Codebehind
WHERE WEB FORMS FALL SHORT
ASP.NET MVC
� It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
� It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
� MVC provides better support for test-driven development (TDD).
� It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.
ADVANTAGES OF AN MVC-BASED
APPLICATION
ASP.NET MVC
� Guiding tenets:
� Be extensible, maintainable, and flexible
� Be testable
� Get out of the user ’s way when necessary
� Serving methods, not files
� URL routes are defined to target controllers and methods rather than specific aspx pages with load events
ASP.NET MVC BELIEFS
ASP.NET MVC
� To effectively use MVC, adhere to the following best practices:
� The model should be a simple object with read and write properties to support a single view.
� The view should focus on standards-based markup.
� Logic in the view should be limited to user interaction and not include business logic.
� Controllers should not know anything about how the data in the model is manipulated in the view.
� Controllers should not know anything about how the data is persisted beyond the model.
ASP.NET MVC
MVC BEST PRACTICES
THE MVC PATTERN
ASP.NET MVC
� The Model represents a set of classes that describes the business logic and data. It also defines business rules for how the data can be changed and manipulated.
� Models in ASP.NET MVC, handle the Data Access Layer by using ORM tools like Entity Framework or NHibernate etc.
� Totally independent from the views or the controllers
� Model state can be stored in memory, database and XML files
MODEL
ASP.NET MVC
us ing System;us ing System.Col lect ions .Gener ic ;us ing System.ComponentModel .DataAnnotat ions ;
namespace Demo.Model{
publ ic c lass Student{
publ ic int ID { get ; set ; }publ ic s t r ing LastName { get ; set ; }publ ic s t r ing F i r s tMidName { get ; set ; }[DataType(DataType.Date) ][Disp layFormat(DataFormatStr ing = " {0 :yyyy-MM-dd}" , ApplyFormat InEditMode
= t rue) ]publ ic DateTime Enro l lmentDate { get ; set ; }
publ ic v i r tual ICo l lect ion<Enrol lment> Enro l lments { get ; set ; }}
}
ASP.NET MVC
MODEL EXAMPLE
� The View is responsible for transforming a model or models into UI. The Model is responsible for providing all the required business logic and validation to the view. The view is only responsible for displaying the data, that is received from the controller as the result.
� Views in ASP.NET MVC, handle the UI presentation of data as the result of a request received by a controller.
� No interaction with the models or the controllers
� Views can be strongly typed
VIEW
ASP.NET MVC
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>Hello from our View Template!</p>
ASP.NET MVC
VIEW EXAMPLE
� The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View.
� A controller is made up of methods called Action methods which can act as an intermediary between the DAL and return a fully populated view.
� Controllers in ASP.NET MVC, respond to HTTP requests and determine the action to take based upon the content of the incoming request.
� Form data from a View can be submitted to a controller ’s action method as a strongly typed object.
CONTROLLER
ASP.NET MVC
us ing System;us ing System.Col lect ions .Gener ic ;us ing System.L inq;us ing System.Web;us ing System.Web.Mvc;us ing System.Web.Mvc.Ajax ;
namespace Demo.Contro l lers{
publ ic c lass StudentControl ler : Control ler{
publ ic Act ionResult Index( ){
/ / Add act ion logic herereturn V iew() ;
}
}}
ASP.NET MVC
CONTROLLER EXAMPLE
� ASP.NET MVC offers us three options for preserving data - ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibil ity.
� Difference between ViewBag & ViewData:� ViewData is a dictionary of objects that is derived from ViewDataDictionaryclass and is accessible using strings as keys.
� ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
� ViewData requires typecasting for complex data type and check for null values to avoid error.
� ViewBag doesn’t require typecasting for complex data type.
� TempData is also a dictionary derived from TempDataDictionary class and stored in shor t l ives session and it is a string key and object value. The difference is the l i fe cycle of the object. TempData keeps the information for the t ime of an HTTP Request. This mean only from one page to another.
ASP.NET MVC
PRESERVING DATA
FILTERS IN MVC
ASP.NET MVC
� The ASP.NET MVC framework supports f ive different types of f i lters which are executed in the following order :� Authentication filters – Used to implement authentication tasks to determine if a user is authenticated before executing the controller action.
� Authorization filters - Used to implement authorization for authenticated users to determine if a user is authorized to execute the controller action.
� Action filters - Contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
� Result filters - Contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
� Exception filters - You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
MVC FILTERS IN ACTION
ASP.NET MVC
� Filters can be applied at 3 levels within the application:
� Global Level – Filter is applied to all controller actions within the application
� Controller Level – Filter is applied to all actions within the specific controller.
� Action Method Level – Filter is only applied to an individual action method.
ASP.NET MVC
FILTER REGISTRATION
� This filter provides authorization logic to determine if a user is authorized to execute the Action method request on the Controller. It will be executed before the action gets executed.
ASP.NET MVC
AUTHORIZATION FILTER
� C o d e :p u b l i c c l a s s C u s t omAu t h o r i z e A t t r i b u t e : A u t h o r i z e A t t r i b u t e{
E n t i t i e s c o n t e x t = n ew E n t i t i e s ( ) ; / / m y e n t i t yp r i v a t e r e a d o n l y s t r i n g [ ] a l l o w e d r o l e s ;p u b l i c C u s t omAu t h o r i z e A t t r i b u t e (p a r am s s t r i n g [ ] r o l e s ){
t h i s . a l l o w e d r o l e s = r o l e s ;}p r o t e c t e d o v e r r i d e b o o l A u t h o r i z e C o r e ( H t t p C o n t e x t B a s e h t t p C o n t e x t ){
b o o l a u t h o r i z e = f a l s e ;f o r e a c h ( v a r r o l e i n a l l o w e d r o l e s ){
v a r u s e r = c o n t e x t . A p p U s e r .W h e r e (m => m . U s e r I D = = G e t U s e r . C u r r e n t U s e r && m . R o l e = = r o l e &&m . I s A c t i v e = = t r u e ) ; / / c h e c k i n g a c t i v e u s e r s w i t h a l l o w e d r o l e s .i f ( u s e r . C o u n t ( ) > 0 ){
a u t h o r i z e = t r u e ; / * r e t u r n t r u e i f E n t i t y h a s c u r r e n t u s e r ( a c t i v e ) w i t h s p e c i f i c r o l e * /}
}r e t u r n a u t h o r i z e ;
}p r o t e c t e d o v e r r i d e v o i d H a n d l e U n a u t h o r i z e d R e q u e s t ( A u t h o r i z a t i o n C o n t e x t f i l t e r C o n t e x t ){
f i l t e r C o n t e x t . R e s u l t = n ew H t t p U n a u t h o r i z e d R e s u l t ( ) ;}
}� U s a g e :[ C u s t omA u t h o r i z e ( “ A dm i n i s t r a t o r ” , ” Mo d e r a t o r ” )p u b l i c A c t i o n R e s u l t A d d A r t i c l e ( ){r e t u r n V i e w ( ) ;}
ASP.NET MVC
AUTHORIZATION FILTER EXAMPLE
� This f i l ter wi l l be invoked whenever a control ler or act ion of the contro l ler throws an except ion. This i s par t icular ly usefu l when we need custom error logging module .
� F i l ter s can be appl ied g loba l ly, to a s ingle act ion or a l l act ions with in a s ingle control ler.
� Example:[HandleError (Except ionType = typeof(Appl icat ionException) , V iew = "Error") ] publ ic c lass HomeContro l ler : Contro l ler{
publ ic Act ionResult Index( ){
V iewData["Message"] = "Welcome to ASP.NET MVC!" ;
return V iew() ;}
publ ic Act ionResult About( ){
return V iew() ;}
}
ASP.NET MVC
APPLYING AN EXCEPTION FILTER
� This f i lter wil l execute before and af ter the result of the action method has been executed. We can use this f i lter if we want some modification to be done in the action's result .
� Example:
publ ic c lass Prof i leResul tAttr ibute : F i l terAtt r ibute , IResul tF i l ter {pr ivate Stopwatch t imer ;
publ ic vo id OnResultExecut ing(ResultExecut ingContext f i l terContext) {t imer = Stopwatch.Star tNew() ;
}
publ ic vo id OnResultExecuted(Resul tExecutedContext f i l terContext) {t imer.Stop( ) ;f i l terContext .HttpContext .Response.Wri te(s t r ing .Format(“{0} seconds" , t imer.E lapsed.TotalSeconds) ) ;
}}
ASP.NET MVC
RESULT FILTER
ROUTING IN MVC
ASP.NET MVC
� Rout ing is a pat tern matching system that monitors the incoming request and determines what to do with that request .
� At runt ime, the rout ing engine uses the route tab le for matching the incoming request 's URL pat tern aga inst the URL pat terns def ined in the route tab le .
� MVCs rout ing implementat ion f rees up URLs f rom physica l assoc iat ion to a f i le thus opening up a LOT of f lex ibi l i ty with how URLs can be presented and interpreted in an MVC appl icat ion.
� Urls are va l idated aga inst the route tab le in sequent ia l order, the f i r s t route that matches the ur l s t ructure wi l l be appl ied.
� Rout ing can be used for SEO to create an intu i t ive semant ic URL to spec i f ic page content .
� Example :� Routing Table Entr y:
Rou te s .MapRou te ( name : “Cus t omerLookup” , u r l : “ { c on t ro l l e r } / {a c t i on } / { i d } ” ,d e f au l t s : n ew { con t ro l l e r = “Cus t omer s ” , a c t i on=“Lookup ” , i d = U r l Pa ramete r .Op t i ona l } ) ;
� Routed URL Breakdown: http:// localhost/MVCDev/Customers/Lookup/32� localhost – webserver� MVCDev - website� Customers– Controller� Lookup – Method� 32 – Parameter (Customer ID to find)
ROUTING AND SEO
ASP.NET MVC
SCAFFOLDING IN MVC
ASP.NET MVC
� ASP.NET scaffolding is a code generation framework
� Works with the entity framework to generate pages that are fully functional and include display, insert, edit, delete, sorting and paging functionality (basic CRUD operations)
� Minimal or no code to create data-driven web applications
� Quick development time
� Built-in data validation that is based on the database schema
� Filters that are created for each foreign key or Boolean fields
� Utilizes T4 templates which can be created and modified to fit your code generation needs
WHAT IS SCAFFOLDING?
ASP.NET MVC
ASP.NET MVC
REAL WORLD
FINDINGS
� Took an existing webforms project and converted the most complex user intensive page to MVC.
� Online calculator that allowed users to request quotes, track resulting information and update budget information.
� 11 Javascript and 10 CSS files including various plugins and libraries
� jQuery 1.10.2
� Bootstrap 3.0.0
� Modernizr 2.6.2
ASP.NET MVC
PROJECT BACKGROUND
UI Code Behind
Master Page 479 99
7 Web Services 1798 135
Page 294 373
Total 2571 607
ASP.NET MVC
PROJECT CODE LINE COUNTS
UI Code Behind
Master Page 484 67
7 Web Services 685 85
Page 252 154
Total 1421 306
Web Forms
MVC
Web Forms
� 2381 lines of html, javascript & cssrendered to the browser
�WebResource.axd (.NET Controls), ScriptResource.axd (AJAX) & .NET Toolkit Combined Scripts
� Viewstate
MVC
ASP.NET MVC
RENDERING CONTENT
� 1017 lines of html, javascript & cssrendered to the browser
�Minified css & js
� Razor syntax allowed for streamlined html content
� No Viewstate
WebForms
Script Async Time
Jquery.js 42ms
WebResource.axd 38ms
ScriptResource.axd 39ms
Bootstrap.js 44ms
Plugins.js 43ms
Modernizr.js 47ms
Jquery.browser 48ms
Functions.js 52ms
Moment.js 52ms
Main.js 51ms
Jquery.cookie 50ms
Jquery.ui 52ms
Calculator?CombinedScripts 89ms
MVC
Script Async Time
Jquery (jquery & jquery ui) 33ms
Bootstrap 33ms
Functions 33ms
Js (plugins, main, moment, jquery.cookie, jquery.browser, modernizr)
32ms
ASP.NET MVC
JAVASCRIPT BUNDLING
WebForms
CSS Async
Bootstrap 30ms
Bootstrap-theme 31ms
Font-awesome 245ms
Fuelux 33ms
Custom 33ms
Spinner 34ms
Css?fontfamily 85ms
Main.css 33ms
Jquery-ui 35ms
Jquery-ui.theme 35ms
MVC
Bundle Async
Font-awesome 49ms
Css?fontfamily 80ms
Style (bootstrap, bootstrap-theme, fuelux,main, custom, spinner, jquery-ui, jquery-ui.theme)
35ms
ASP.NET MVC
CSS BUNDLING
Page Body Content (Bytes) HTML Line Counts (Lines)
ASP.NET MVC
PROJECT OUTCOME
ASP.NET Webforms (31,646 bytes)
MVC (12,911 bytes)
ASP.NET Webforms (2,381 lines)
MVC (1,017 lines)
Page Load Time (ms) AJAX Callback Sizes (Bytes)
ASP.NET MVC
PROJECT OUTCOME
ASP.NET Webforms (995ms)
MVC (620ms)ASP.NET Webforms (248kb) MVC (82kb)
ASP.NET MVC
Q & A
ASP.NET MVC