Asp.net mvc

35
ASP.NET MVC CRUSH COURSE ERDEM ERGİN

description

ASP.NET MVC presentation beginner to intermediate level

Transcript of Asp.net mvc

Page 1: Asp.net mvc

ASP.NET MVC CRUSH COURSEERDEM ERGİN

Page 2: Asp.net mvc

MVC Pattern – What is it?

► MVC - Acronym for Model/View/Controller► Invented by Trygve Reenskaug [1973 - 1978]► Originally used as an architectural pattern for GUIs.

► The first implementation of MVC was as part of Smalltalk-80

class library.

Page 3: Asp.net mvc

3

Model

View

Controller

1

5

2

4

3

User

The request hits the controller

The Controller asks the Model for data

The Model gives the data back to the Controller

The controller formats the data and passes them to the View

The view renders the HTML that needs to be sent to the

client

MVC Pattern – How does it work?

Page 4: Asp.net mvc

MVC Pattern – Who uses it?

► .NET has Spring.NET, MonoRail► Java has Swing, Struts, Grails and others► Perl has Catalyst, Gantry, Jifty and others

► PHP has Zend, Zoop, Agavi and others► Python has Django, Gluon, Pylon and others

► Ruby has Ruby on Rails► Apple has cocoa and cocoa touch for objective-c [Mac, iPhone]

Page 5: Asp.net mvc

Based on Python

1970S

2003 RoR

{ ASP.NET MVC }

2009.3 MVC1

2010.4 MVC2

MVC FrameworkHistory

….

Page 6: Asp.net mvc

ASP.NET MVC

• It’s not a replacement for asp.net webforms, it’s a new option [flavor]• No more “postbacks” and “ViewStates”• Built on top of ASP.NET

Advantages• Clean URLs and HTML• More control over your html

and JavaScript• Friendly URLS• More easily Testable

Framework.• All ASP.Net providers still

work [Membership, Session, Caching, etc]

• Extensible and Pluggable [Support replacing any component]

Page 7: Asp.net mvc

ASP.NET MVC Framework Structure

ASP.NET Routing(System.Web.Routing.dll)

ASP.NET Abstractions(System.Web.Abstractions.dll)

ASP.NET MVC(System.Web.Mvc.dll)

Page 8: Asp.net mvc

ASP.NET MVC Execution Process

Request

URLRouting

Route

RouteHandler

HttpHandler

Controller Factory

Controller

Action

ViewFactory View

Response

Page 9: Asp.net mvc

DEMO

► Create New ASP.NET MVC Project► Investigate ASP.NET MVC Structure

Page 10: Asp.net mvc

RoutingR => the hidden character

MVC+R

Page 11: Asp.net mvc

ASP.NET MVC Routing

► URL Patterns► Setting Default Values for URL Parameters► Adding Constraints to Routes► Scenarios When Routing Is Not Applied► How URLs Are Matched to Routes► Accessing URL Parameters in a Routed Page► ASP.NET Routing and Security► ASP.NET Routing versus URL Rewriting

Page 12: Asp.net mvc

Model [M]

Validation

Page 13: Asp.net mvc

Controller [C]Controlling the flow of application execution

Page 14: Asp.net mvc

ASP.NET MVC Controller

► Controller is a class consisting of a set of action methods.

► Responsible for – Handling user interaction– Working with the models– Selecting a view to render– Sending model and information to a particular view

– Making decisions for security, UI, redirects ... etc.

► The ASP.Net MVC requires the names of all controllers to end with the suffix "Controller“ e.g. HomeController, LoginController

Page 15: Asp.net mvc

ASP.NET MVC Controller

Action return ActionResult which can be • ViewResult => HTML and markup. • EmptyResult => no result. • RedirectResult => redirection to a new URL. • JsonResult => json result that can be used in an AJAX application.

• JavaScriptResult => JavaScript script. • ContentResult => text result [and wraps any non

ActionResult return Type]. • FileContentResult => downloadable file [with the binary

content]. • FilePathResult => downloadable file [with a path]. • FileStreamResult => a downloadable file [with a file

stream].

A controller action always returns an ActionResultWhat if I return an object ??

Note: all public methods of a controller class considered as action methods, if you don’t want a public method to be an action, mark it with [NonAction()] attribute

Page 16: Asp.net mvc

ASP.NET MVC Controller Filter

Page 17: Asp.net mvc

View [V]

Page 18: Asp.net mvc

ASP.NET MVC View

► Responsible for presentation, look & feel, formatting, sorting … etc.

► Interacts with model but shouldn’t make decisions

► No logic should go there► Code Behind exists but not recommended► No View State, No Server Controls► HTML Helpers► Takes the view data from the controller► Can be strong typed ► Can be extended by implementing View Engines

► Always build your views !!!

Page 19: Asp.net mvc

• Html.ActionLink()• Html.BeginForm()• Html.CheckBox()•

Html.DropDownList()

• Html.EndForm()• Html.Hidden()

An HTML Helper is just a method that returns a string.

• Html.ListBox()• Html.Password()• Html.RadioButton()• Html.TextArea()• Html.TextBox()

e.g.

ASP.NET MVC View

Page 20: Asp.net mvc

Extensibility

Page 21: Asp.net mvc

The default ASP.NET MVC Pipeline

Request

URLRouting

Route

RouteHandler

HttpHandler

Controller Factory

Controller

Action

ViewFactory View

Response

21

Page 22: Asp.net mvc

The default components

► URL Routing:– Parses the URL, and instantiate the MvcHandler

► Controller Factory– Takes URL parameters, create controller via reflection based on Controller name

► Action Invoker– Invokes the action based on the name, with the filters before and after

► View Engine– WebForms view engine

► Template– Renders a TextBox almost for everything

► HtmlHelper– Has a bunch of standard methods

Page 23: Asp.net mvc

Routing extensibility

► RouteConstraint– Validates route parameters with code

► RouteHandler– Defines how the request must be handled

Page 24: Asp.net mvc

Controller Extensibility

► ControllerFactory– Responsible for creating Controllers

► ActionInvoker– Invokes an action, based only on its name

► ActionMethodSelector Attribute– Helps the action invoker decide which action to invoke when the name is not unique

► Controller– The base class for every controller

► ActionResult– Decides how to send the output to the user

Page 25: Asp.net mvc

Action Filter Extensibility

► AuthorizationFilter– Makes sure the current request is allowed

► Action Filters– Executed before or after the action executes

► Result Filters– Executed before or after an action result executes

Page 26: Asp.net mvc

Binding/Validation Extensibility

► ModelBinder– Populates the action method parameters from the request

► ModelValidator Provider– Retrieves the validation rules

► Server-side Validation Rules– The actual server-side validation rule

Page 27: Asp.net mvc

View Extensibility

► ViewEngine– The service that transforms in HTML the data for the user

► HtmlHelpers– Utility functions that hide away the generation of some HTML markup or JavaScript code

► Client-side Validation Rules– Client-side validation rules

► ModelMetadata Provider– Retrieves the metadata needed for the templated helpers

► Custom Templates– Renders the html to edit/display specific types

Page 28: Asp.net mvc

The Most important extensibility points

Page 29: Asp.net mvc

Custom T4 Templates

► WHAT: Generates View and Controller files ► DEFAULT: <vsdir>Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates

► WHY: Add your own to generate Views and Controllers based on your needs

► Copy CodeTemplates folder in you solution

Demo

Page 30: Asp.net mvc

Custom Templates

► WHAT: Renders the html to edit/display specific types

► DEFAULT: Everything is a label or a textbox

► WHY: Add your own to customize specific data-types

► Add PartialViews in:– /Views/Shared/DisplayTemplates– /Views/Shared/EditorTemplates

Demo

Page 31: Asp.net mvc

Server-side Validation Rules

► WHAT: Define how a property is validated in the server side validation

► DEFAULT: Required, Length, wrong type► WHY: Add your own rules

► Write a new ValidationAttribute► Implement the IsValid method► Apply attribute to your model

Demo

Page 32: Asp.net mvc

Client-side Validation Rules

► WHAT: Define how a property is validated in the client-side validation

► DEFAULT: Client-side counterparts of the default server-side validators

► WHY: Add your own validators

Page 33: Asp.net mvc

Client-side Validation Rules

► First make a server-side validator► Make validation logic in JavaScript► Write adapter to push validation rules to client-side

► Register validation function via JS► Register adapter in Global.asax

Demo

Page 34: Asp.net mvc

Base Controller

► WHAT: The base class for every Controller► DEFAULT: Default implementation of helper methods

► WHY: Extend if you want to enforce you own conventions

► Override Controller► Your controllers override from BaseController instead of Controller

Demo

Page 35: Asp.net mvc

HtmlHelpers

► WHAT: Utility functions that hide away the generation of HTML markup or JavaScript code

► DEFAULT: Html.TextBox, Html.Encode, Html.Partial, …

► WHY: “If there is an if, write an Helper”

► Add new methods as extension methods

Demo