Asp.net mvc
-
Upload
erdemergin -
Category
Documents
-
view
2.304 -
download
2
description
Transcript of Asp.net mvc
ASP.NET MVC CRUSH COURSEERDEM ERGİN
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.
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?
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]
Based on Python
1970S
2003 RoR
{ ASP.NET MVC }
2009.3 MVC1
2010.4 MVC2
MVC FrameworkHistory
….
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]
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)
ASP.NET MVC Execution Process
Request
URLRouting
Route
RouteHandler
HttpHandler
Controller Factory
Controller
Action
ViewFactory View
Response
DEMO
► Create New ASP.NET MVC Project► Investigate ASP.NET MVC Structure
RoutingR => the hidden character
MVC+R
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
Model [M]
Validation
Controller [C]Controlling the flow of application execution
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
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
ASP.NET MVC Controller Filter
View [V]
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 !!!
• 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
Extensibility
The default ASP.NET MVC Pipeline
Request
URLRouting
Route
RouteHandler
HttpHandler
Controller Factory
Controller
Action
ViewFactory View
Response
21
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
Routing extensibility
► RouteConstraint– Validates route parameters with code
► RouteHandler– Defines how the request must be handled
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
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
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
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
The Most important extensibility points
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
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
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
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
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
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
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