2. Controller
This is what we have learned about ‘controller’ so far:
It is one of the three MVC components
It is a C# class that contains action methods
An action method is a method that runs in response to a request
It is the entry point when a HTTP request is received
Depending on the request, the controller may get the requested data from
the model or update the model data
Then the controller selects a View to display, passing data to it
In this chapter, we will have a closer look at controllers
3. Request, controller and binding model
The first step when the MvcMiddleware receives a request is routing the
request to an appropriate controller
Routing takes the path of the request, and maps it to one of the actions in
the controller
Once an action is selected, if the request has data, a binding model is
generated
A binding model is an object that acts as a “container” for the data
provided in a request
Data could be part of the URL, query string, headers, or form fields
4. Request, controller and binding model
Some action methods do not have parameters, for example a request to
display the home page, like the one below:
public IActionResult Index()
{
}
This action method does not use a binding model, if one is created
However, some action methods have parameters; they are used to receive
data contained in the request
5. Request, controller and binding model
When ‘Submit Order’ is clicked, the request is mapped
to this action of HomeController, because of the
HTTPPost attribute
An object (of the OrderModel type) is created using
the data entered in the Index view (customer, item,
price, quantity). This is the binding model
This object (the binding model) is passed to the action
method. So, the parameter ‘model’ of the Index
method holds the binding model
[HTTPPost]
public IActionResult Index(OrderModel model)
{
ViewBag.AmtDue = model.CalculateAmountDue();
return View();
}
6. Validation
Next, the action method:
1. Validates the data contained in the binding model
2. Invokes the appropriate actions on the application model
3. Generates a response based on the output from the application model
Below is an illustration of Step 1, validation:
public IActionResult Search(OrderModel model)
{
if(ModelState.IsValid)
{
……
return View();
}
return Redirect("/")
}
ModelState is a property inherited from the Controller class
7. Using the application model
Step 2 is illustrated below, from the Order Processing example:
ViewBag.AmtDue = model.CalculateAmountDue();
In this case, our application model consists of a single class, OrderModel
and controller is invoking a method of this class
8. Generating response
Step 3, the action method selects the view template and passes the view
model to it, if applicable
View model is an object required by the view to generate a UI
View model can be one of business logic classes, for example Order class,
or
It can be a class created specifically to represent the structure of the data
needed by a view
We will look at these types of models in the future
9. Action methods
Any public method on a controller acts as an action method
To review, the responsibility of an action method is generally threefold:
Confirm the incoming request is valid
Invoke the appropriate business logic corresponding to the incoming request
Choose the appropriate kind of response to return
An action doesn’t need to perform all of these actions, but at the very least
it must choose the kind of response to return
10. Action methods - Parameters
As we saw earlier, action methods can have parameters
These parameters could be of complex or reference type such as
OrderModel, but
They can also be primitive types, such as string or int
11. Action methods – return type
An action method can return any data type, but in a typical MVC
application, action methods generally return
a ViewResult that the MvcMiddleware will use to generate an HTML response,
or
a RedirectResult, which indicates the user should be redirected to a different
page in your application
Both are subtypes of ActionResult
ActionResult is an abstract class that implements the IActionResult
interface
12. Action methods – return type
For either case (when ViewResult or RedirectResult is returned) you can
also use the IActionResult as return type
However, if your action method returns more than one type, the return
type must be IActionResult
In the validation example in slide 6, the method returns either a ViewResult or
RedirectResult
13. IActionResult
In addition to ViewResult and RedirectResult, ASP.NET Core has other
types of IActionResult:
RedirectToRouteResult
FileResult
ContentResult
StatusCodeResult
NotFoundResult
14. IActionResult
If controller inherits from Controller class:
You can use a number of helper methods to generate response
For example: View() method
View() method has several overloads:
View()
View(model)
View(name)
Name is the name of a specified view
View (name, model)
15. Conventions for controllers
MVC controllers are discovered and used by the MvcMiddleware as long
as they are instantiable (they have a public constructor, aren’t static, and
aren’t abstract) and either:
Have a name ending in “Controller,” for example HomeController
Inherit from the Controller or ControllerBase class (or a class that inherits from
these)
It’s often a good idea to use the Controller class, given that it contains a
number of helper methods for returning results
Another common convention is to place all your controller files in a
Controllers subfolder in your project