Working with Controllers and Actions in MVC

Page 1

Working with Controllers and Actions in MVC

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Objectives • Learn how controllers manage MVC applications • Understand action methods and how they can receive input • Explore how you can return a result from an action method

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Agenda • • • •

Introduction to Controllers Using a Controller to Manage the Application Controller Actions Returning Action Results

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Introduction to Controllers • Controller is the traffic cop to keep things smooth    

Responds to user input Manages overall flow of application Interacts with model to change state and data Selects a result to respond to user

• Does not itself contain UI, data, or business logic code • Ultimately responsible for servicing requests  The application’s logic

• Lots of attention in MVC 3 Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Using a Controller to Manage the Application • Powerful but easy to use • Implemented as .NET class with properties and methods • System.Web.Mvc namespace  Your controllers are likely to need very little code  Routine infrastructure encapsulated in base classes

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Controllers in System.Web.Mvc • Controller must:  Implement IController interface  Have a name ending in “Controller”  Marked public, not abstract, no generic parameters

• Otherwise, not recognized as controller  Methods never called as action methods

• Normally inherit from Controller class  Which inherits from ControllerBase  Which implements IController

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


The IController Interface • IController requirement isn’t onerous • Single purpose: find a controller and call Execute method • Simple interface definition: public interface IController { void Execute(RequestContext requestContext); }

• When request arrives  Routing identifies controller, calls Execute  Passes in object with context information Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


The ControllerBase Abstract Base Class • Implements IController  Adds controller features, such as TempData and ViewData  Execute method creates ControllerContext object

• Still pretty lightweight  Relatively little added functionality  Could build Web site with either IController or ControllerBase

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


The Controller Class • Rich implementation of controller infrastructure • Inherits from ControllerBase  So indirectly implements IController

• Added features include  Action methods  Action results  Filters

• Normally should implement your controllers using Controller Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


The MVC Request Processing Pipeline

• Response process to every user request  IIS, ASP.NET, MVC collaboration Request

HTTP

Routing Engine

Controller Factory

Controller

View

Action Method

Action Invoker

HTTP Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company

Response


Action Method Selection • Job of the action invoker • More complicated than initially appears  Multiple overloaded methods with same name  Decorated with attributes that control use  Action name may be different from method name

• Starts by getting action portion of route {controller}/{action}/{id}  Default action is “Index”

• Then map action name to controller method  Simplest: one method with that action name Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Action Method Qualifications • Method must meet requirements to be action method:  Public and not static or Shared  Cannot be defined on System.Object or Controller o

i.e., ToString() could not be an action method

 Cannot be a special method  Cannot have a NonAction attribute

• Action invoker uses reflection to find candidates  All methods with same action name  But method attributes can make this murky with multiple candidates Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


ActionName Attribute • Normal convention is for controller method name to be same as action name • Can give it a different action name  Action name that is not a legal language name  Use an MVC component name as action name  Different naming standards

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


ActionMethodSelector Attribute • Now action invoker has list of all matching action names • Next examines ActionMethodSelector attributes  Control what conditions a method should be used for a request  Single method: IsValidForRequest o o

Executes on each candidate action method Return false, removed from list

• Implementations  NonAction attribute  AcceptVerbs attribute  HttpDelete, HttpGet, HttpPost, HttpPut Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Controller Actions • Once invoked, action method does its job  Receive and process input  Perform processing  Generate output o o o o

Select a view Write output directly to page Raw data to browser Do nothing

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Action Method Input • Most methods need data to do work • Can come from a variety of sources     

Environment Operating system Nature of user request Direct parameters Many others

• Three broad sources for action method  Context objects  Method parameters  Model bindings Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Context Object Input • Web requests come loaded with information     

HTTP headers User information Browser and capability information User’s IP address Authentication information

• Information available through context objects

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Parameter Input • Specialized input customized for method • MVC takes care of populating values • Action invoker examines context objects for parameter values and uses model binder 1. Request.Form 2. RouteData.Values 3. Request.QueryString

• Matches solely by name in order  

Once it finds a match it stops searching Have to coordinate names to avoid duplicate names Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Model Bindings • Model encapsulates data and business rules  Use directly in controllers and views  Built-in features to make easy  Automatic data scaffolding

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Controller Session State • SessionState attribute  Control how and whether controller uses session state  MVC uses session state by default, if available

• SessionStateBehavior enumeration    

Default Disabled ReadOnly Required

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Returning Action Results • Action method follows a normal process  Receives request and data  Process the request  Generates response

• Many possible responses • Three broad types of results  HTML  Redirect somewhere else  Page data

• All options based on ActionResult Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Action Result • ActionResult base class public abstract class ActionResult { public abstract void ExecuteResult(ControllerContext context); }

• ExecuteResult receives context information • Takes care of low-level work of generating a response

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


ActionResult Types Type

Helper Method

Description

ContentResult

Content()

Raw text data

EmptyResult

--

Returns nothing

FileResult

File()

Base class to send file

HttpNotFoundResult

HttpNotFound()

Returns HTTP 404

HttpStatusCodeResult

--

Returns any HTTP status

HttpUnauthorizedResult

--

Returns HTTP 401

JavaScriptResult

JavaScript()

Returns and executes script

JsonResult

Json()

JavaScript Object Notation

PartialViewResult

PartialView()

HTML snippet

RedirectResult

Redirect()

Redirect to URL

RedirectToRouteResult

RedirectToRoute() RedirectToAction()

Redirect to MVC route or action

ViewResult

View()

Full HTML page

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Passing Data to the View • Use either ViewData or ViewBag     

Different faces of the same feature A bit like ASP.NET Session object Exposes ViewDataDictionary But ViewData/ViewBag disappear after view rendered Session lasts for the user session

• ViewData is loosely typed • ViewBag is strongly typed  Uses dynamic language feature of C# and VB

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


ViewData and ViewBag • Not limited to passing strings • Keep in mind that they are same feature, but different  Can mix and match in one action method/view  Get the same result either way  Generally should use ViewBag

• But in VB, using in controller requires setting Option Strict Off

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Returning Text Data: ContentResult • HTML is dominant data format  But browsers can deal with variety of formats

• Use a ContentResult for other formats  Content helper method  Specify content as string  Optionally specify type, such as text/xml

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Implicit Action Results • Return text and don’t need to specify type • If type is not string, calls ToString method with InvariantCulture setting  Wraps in ContentResult object

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Missing Resource: HttpNotFoundResult

• Useful to indicate that requested resource is not available  User hacks a URL

• Returns HTTP 404 status code  Can mask an exception that an attacker could otherwise use

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Return any HTTP Status Code: HttpStatusCodeResult • More flexible than HttpNotFoundResult • Can specify any HTTP status code  Optional description

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Redirection Methods • Methods on the Controller class • Return instances of redirection action methods  Permanent property set to true

• Types  RedirectPermanent method  RedirectToRoutePermanent method  RedirectToActionPermanent method

• Make easy to manage permanent redirections  HTTP 301 status code Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Learn More! • This is an excerpt from a larger course. Visit www.learnnowonline.com for the full details!

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.