Controller
Nguyen Ha Giang
1
2
Objectives
• Define and describe controllers
• Describe how to work with action methods
• Explain how to invoke action methods
• Explain routing requests
• Describe URL patterns
3
Working with Controllers
• A controller, in an ASP.NET app does the
following
– Manages the flow of the app.
– Is responsible for intercepting incoming
requests and executing the appropriate app code.
– Communicate with the models of the app and
selects the required view to be rendered for the request.
– Is a C# class that extends the Controller class
of the System.Web.Mvc namespace.
– Allows separating the business logic of the app
from the presentation logic.
4
Working with Controllers
• A controller is responsible to:
– Locate the appropriate method to call for an
incoming request.
– Validate the data of the incoming request before invoking the requested method.
– Retrieve the request data and passing it to
requested method as arguments.
– Handle any exceptions that the requested
method throws.
– Help in rendering the view based on the result
of the requested method.
5
Creating a Controller
•
In ASP.NET MVC, the ControllerBase class of the System.Web.Mvc namespace is the base class for all controllers.
• The Controllers class extends the
ControllerBase class to provide a default implementation of a controller.
• To create a controller in an ASP.NET MVC app, you will need to create a C# class that extends the Controller class.
•
Instead of creating a controller manually, you can use VS 2013 IDE, which also
creates the folder structure for the
application automatically.
6
Creating a Controller
•
In VS 2013 IDE, you can create a controller by performing the following steps:
– Right-click the Controllers folder in the Solution
Explorer window.
– Select Add (cid:0)
Controller from the context menu
that appears. The Add Scaffold dialog box is displayed.
7
Creating a Controller
• Select the Empty MVC Controller in
scaffolding options.
• Type TestController in the controller name
• Click Add. The solution Explorer window displays the newly created TestController controller under the Controllers folder.
8
Creating a Controller
• Following figure shows the Solution Explorer window that displays the newly created controller under the Controllers folder:
9
Creating a Controller
• Following is the skeleton code of a
Controller class:
using System.Web.Mvc;
namespace MVCDemo.Controllers { public class TestController : Controller { public ActionResult Index() { return View(); }
} }
10
Working with Action methods
• A controller class can contains one or more action methods, also known as controller actions.
• Action methods:
– Are responsible for processing the requests
that are sent to the controller.
– Typically returns an ActionResult object that encapsulates the result of executing the method.
• Following figure shows the working of
action methods
11
Working with Action methods
1 HTTP Request URL
http://mvcexample.com/Home/Index
MVC Framework
2 Invoke
HomeController
3 ActionResult
4 HTTP Response
Web Browser Index() Action Method
12
Working with Action methods
• The steps in the preceding figure are as
follows:
– The browser sends an HTTP request.
– The MVC Framework invokes the controller action method based on the request URL.
– The action method executes and returns an
ActionResult object. This object encapsulates the result of the action method execution.
– The MVC Framework convert an ActionResult to HTTP response and sends the response back to the browser.
13
Working with Action Methods
• Rule that you need to consider while
creating an action method are as follows:
– They must be declared as public
– They cannot be declared as static
– They cannot have overloaded versions based
on parameters
• Following is the syntax for creating an
action method in a Controller class:
public ActionResult
14
Working with Action Methods
• Following code creates two action methods with the name Index and About in the HomeController controller class:
• The code creates 2 action methods, named Index and
About in the HomeController controller class. Both these action methods are declared as public and to return ActionResult objects
using System.Web.Mvc; public class TestController : Controller { public ActionResult Index() { // TODO HERE return View(); } public ActionResult About() { // TODO HERE return View(); }
}
15
Working with Action Methods
• Although, most of the action methods return an ActionResult object, an action method can also return other types, such as String, int, or bool, as shown in the following code:
using System.Web.Mvc; public class TestController : Controller { public string Index() { return "Hi World"; } public int About() { return 123; } }
16
Action Results
• ActionResult:
– Is an abstract base class for all implementing classes that provides different types of results.
– Consits of HTML in combination with server-
side and client-side scripts to respond to user actions.
• Following table shows the commonly used classes that extend the ActionResult class to provide different implementations of the results of an method:
17
Action Results
Classes Description
ViewResult Render a view as an HTML document
PartialViewResult Render a partial view, which is a sub-view of main view
EmptyResult Returns an empty response
RedirectResult Redirect a response to another action method
JsonResult Return the result as JSON
JavaScriptResult Returns JS that executes on the client browser
ContentResult
Returns the content based on a defined content type, such as XML
FileContentResult Returns the content of a binary file
FileStreamResult Returns the content of a file using a Stream object
FilePathResult Returns a file as a response
18
Invoking Action Methods
•
In an ASP.NET MVC app, you can create multiple action methods in a controller.
• You can invoke an action method by specifying a
URL in the Web browser containing the name of
the controller and the action method to invoke.
http://
• Where,
–
app
–
without the Controller suffix
–
action method to invoke.
19
Invoking Action Methods
• Consider the following URL:
http://mvcexample.com/home/Registration
• When this URL is sent to the app through a Web browser, the MVC framework perform the following tasks:
– Searches for the HomeController controller
class
– Searches for the Registration() action method in
the HomeController controller class
– Executes the Registration() action method
– Returns the response back to the browser
20
Invoking Action Methods
Application hosted on http//mvcexample.com/Home/Registration
HTTP Request URL
http://mvcexample.com/Home/Registration
HomeController
1
2
Registration() Action Method
3
4 HTTP Response
Web Browser
21
Passing Parameters
• Sometimes you may need to provide input
other than the Web page name while requesting for a Web pages
• Consider the following URL:
– http://www.mvcexample.com/student/details?
Id=007
– The preceding URL will invoke the Details action method of the StudentController controller class.
– The URL also contains an Id parameter with the
value 007.
• The Details action method must accept an
Id parameter of type string in order to return
student records based on the Id value.
22
Passing Parameters
• Following code shows the Details action
that accepts an Id parameter:
public ActionResult Details(int Id) { /*Return student records based on the Id parameter as an ActionResult object*/ }
23
Routing Requests
• MVC Framework introduces routing that allows you to define URL patterns with placeholders that maps to request URLs pattern.
•
In an ASP.NET MVC app, routing:
– Defines how the app will process and respond
to incoming HTTP request
– Properly describes the controller action to which the requested needs to be routed.
24
Uses of Routing
• Routing is a process that maps incoming requests to specified controller actions.
• Two main functions of routing are as
follows:
– Mapping incoming requests to controller action
– Constructing outgoing URLs correspoding to
controller actions.
• Routing is achieved by configuring route
patterns in the app, that includes:
– Creating the route patterns
– Registering the patterns with the route table of
the MVC Framework
• Route tables provides the information on
how the routing engine process requests
that matches those patterns
25
The Default Route
• An MVC app requires a route to handle
user request.
• When you create an ASP.NET MVC in VS
2013, a route is automatically configured in the RouteConfig.cs file.
• Following code shows the MapRoute()
method
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home",
action = "Index", id = UrlParameter.Optional });
26
The Default Route
• The routes is of type
System.Web.Routing.RouteCollection represents a collection of routes for the app
• The MapRoute() method defines a route named Default, a URL pattern, and a default route.
• The default route is used if the request URL
does not match with the defined URL pattern defined in the MapRoute() method.
• For example, if a request URL does not contain the name of a controller and an
action, the request will be routed to the
Index action of the Home controller
27
URL Patterns
• URL pattern:
– Is required to be defined when you create a
route.
– Is compared with the URL of a request by the
route engine of the MVC Framework.
– Contains literal values and placeholders
separated by the slash (/) character. Following is an example of the URL Pattern: "{controller}/ {action}/{id}" http://www.mvcexample.com/student/records/36 • URL that will match the preceding pattern: controller controller
action
28
URL Patterns
• A URL parameter can also have a combination of literal values and placeholders.
"S tude nt/{ac tio n}/{id}"
• Some of the URLs that will match with the
preceding URL pattern are:
– http://www.mvcexample.com/student/records/4
9
– http://www.mvcexample.com/student/delete/35
– http://www.mvcexample.com/student/view/16
29
Ordering Routes
• Sometimes you may need to register
multiple routes in an ASP.NET MVC App.
• For that you can configure the sequence in
which the routes will execute
• A route engine start matching a request
URL with a URL pattern starting from the first registered route
• When a matching route is encountered the route engine stops the matching process
30
Ordering Routes
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Student", action = "Index"}); routes.MapRoute( name: "Student", url: "Student/{action}", defaults: new { controller = "Student", action = • Contains 2 placeholders and sets the "Browse"});
default value of the controller parameter to Home and the action parameter to Index.
• Second route contains a literal, Student, and a placeholder, and sets the default value of the controller parameter to Student and the action parameter to Browse
31
Summary
• A controller is responsible for intercepting
incoming requests and executing the appropriate app code
• To create a controller in an ASP.NET MVC app, you will need to create a C# class that extends the Controller class
• A controller class can contains one or more action methods, also known as controller actions
• Although, most action methods return an
ActionResult object, an action method can
also return other types, such as string, int,
or bool
• Routing is a process that maps incoming
requests to specified controller actions
• When you create a route, you need to

