Controllers getting started (introducing the Controller)
Each request for an application is processed by the controller. The controller selects an appropriate method to process the request as long as it does not deviate from the region in which the view and model are responsible. This means that we should not put the business or data storage logic in controllers, nor create user interfaces.
In the ASP. net mvc Framework, controllers contains the. NET class necessary to process requests. The role of controller is to encapsulate our application logic. This means that the Controller is responsible for processing requests, performing model operations, and selecting view to present to users. This note will introduce how controllers is implemented and how we can receive and create outputs.
The MVC Framework does not limit the creation of HTML through view, and other available options will be discussed. It also shows how the actions method simplifies unit testing and explains how to test each result produced by actions.
The following describes how to create a project named controllersandactions and select empty template.
1. Create a controller that implements icontroller
In the MVC Framework, the Controller class must implement the icontroller interface:
Public interface icontroller {void execute (requestcontext );}
This is a very simple interface with only one execute method. It is called when a request is hit in the Controller class. The MVC framework reads the value of the controller attribute created by routing data to know which controller class is hit. We can create a controller class through implementing the icontroller interface, but this is a very low-level interface, and we have to do a lot of work to make the Controller available.
The following basiccontroller provides an example.
View code
namespace ControllersAndActions.Controllers
{
public class BasicController:IController
{
public void Execute(RequestContext requestContext)
{
string controller = (string)requestContext.RouteData.Values["controller"];
string action = (string)requestContext.RouteData.Values["action"];
requestContext.HttpContext.Response.Write(string.Format("Controller:{0},Action:{1}", controller, action));
}
}
}
In the above execute method, we read the values of the controller and action variables from the routedata object of the associated request and write them into the output results. If we run the program and enter:
/Basic/index:
By implementing the icontroller interface, we can create a class which is recognized as a controller by the MVC Framework and sent a request to it. However, it is very difficult to write a responsible application. The MVC Framework does not specifically refer to how a controller processes requests. This also means that we can create any method.
2. Create a controller that inherits the Controller class
The MVC framework is customizable and scalable without restrictions. We can implement the icontroller interface to create any controller class that we need for request processing and result generation. if we do not want to operate on the method or view, we can put everything in our own hands and write a better, faster, and more elegant way to process requests, or we can also extract the controller from the system. web. MVC. controller, so that you can use the functions provided by the MVC framework.
The system. Web. MVC. Controller class provides three key functions:
① Action methods: the behavior of a controller class is divided into multiple methods. Each method is exposed to different URLs and called using parameters extracted from the request, these methods are called Action methods.
② Action results: Return Value of Action Methods
③ Filters: encapsulate reusable behaviors. You only need to add [attributes] to the Controller and action methods for use.
Next, create a derivedcontroller class and inherit the Controller as follows:
View code
public class DerivedController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Hello from DerivedController Index Method";
return View("Index");
}
}
Receiving input)
The controller needs to frequently access incoming data, such as querystring, and parse parameter values through the routing system. There are three main ways to access such data:
① Extract from the context object ② passed as a parameter to the Action Method ③ clearly call the model binding function of the framework
PS: The parameter name is case-insensitive. For example, request. Form ["city"] is the same as request. Form ["city.
Here we mainly use the previous two methods. Model binding will be described in the following sections.
1. Get data from the context object
When we create a controller derived from the Controller base class, we can access a set of very convenient attributes, including: request, response, routedata, httpcontext, Server
Each attribute provides one aspect of the request. These attributes are in the controllercontext instance. In the action method, you can use any context object to access these attributes. For example:
View code
Public actionresult renameproduct ()
{
// Just to demonstrate some attributes
String username = user. Identity. Name;
String servername = server. machinename;
String clientip = request. userhostaddress;
Datetime datestamp = httpcontext. timestamp;
String oldproductname = request. Form ["oldname"];
String newproductname = request. Form ["newname"];
Return view ("Index ");
}
2. Parameters Using the Action Method
This method is more elegant than the previous method, which makes our action method easier to read. The following is a comparison:
View code
// Display weather preparation
Public actionresult showweatherforecast (){
String city = routedata. Values ["city"];
Datetime fordate = datetime. parse (request. Form ["fordate"]);
// Implementation...
}
// We can rewrite it.
Public actionresult showweatherforecast (string city, datetime fordate ){
// Implementation
}
// Is this method more elegant and easier to read than above?
In fact, it is not only easy to read but also conducive to unit testing. One thing we need to note is that the action method does not allow ref or out parameters. During this compilation, no error is reported, but an exception is thrown during running. Example:
public ActionResult Index(out int a)
{
ViewBag.Message = "Hello from DerivedController Index Method";
a = 1;
ViewBag.Num = a;
return View("Index");
}
The code in the index view is as follows:
View code
@{
ViewBag.Title = "MyView";
}
MyViewMessage:@ViewBag.Message<br />
Num:@ViewBag.Num
Run the following exception:
Understand how parameter objects are instantiated
The controller base class uses the value providers (value provider) and model Binders (model binding) components of the MVC Framework to obtain the value of the action method parameter.
Value providers presents available data items to the Controller, and has built-in value providers to obtain data items from request. Form, request. querystring, request. Files, routedata. values. Then these values are passed to model binders to map these values to the types of parameters required by the Action method. The default model binders can create and populate any. Net type objects, and contain custom types and collections.
Understand optional and required parameters
If the MVC framework cannot find a value of the reference type parameter, the action method is still called, but the null value is used. If a value of the value type is not found, an exception will occur and the Action method will not be called.
① The slave parameter of the value type must be assigned a value. If you want this to be the same as the reference type, you can define Int ?, If no value is found, null is passed instead of an exception.
② Parameters of the reference type are optional. To make it mandatory (ensure that a non-null value is passed), add some code above the Action Method to reject the null value.
Specify the default parameter value
If we want to process a request that does not contain the value of the action method parameter, but do not want to check the null value. In this case, you can use the C # optional parameter features as follows:
Public actionresult search (string query = "all", int page = 1 ){...}
Today's note is here. The next note is about this part. Please correct the mistakes in the notes. Thank you!
Good night!