Original: MVC 5 + EF6 Full Tutorial 16--Controller details
As a bridge between the persistence layer and the presentation layer, the controller encapsulates the logic of the application and is one of the core components of MVC.
In this article we will talk about Controller, mainly discuss two aspects:
- Introduction to controller operating mechanism
- Controller data Transfer method
Introduction to controller running mechanism implementing a custom controller
There are two ways to implement a controller ourselves:
One is to inherit the IController interface, one is to inherit the controller or controllerbase.
Controller inherits the Controllerbase, and the controller and controllerbase themselves inherit the IController, in short, need to implement the IController interface.
First we go to Xengine to open a controller, such as AccountController,
When you see the new controller, the scaffolding helps us inherit the controller class.
We step through the following graphs, right-click on the controller definition-view controllerbase definition, and view the IController definition, You can see that the controller needs to implement the Execute method in IController.
Next, we will create a new class Mycustomcontroller, inherit the IController interface, implement the Execute method.
namespace XEngine.Web.Controllers{ public class MyCustomController:IController { public void Execute(RequestContext requestContext) { requestContext.HttpContext.Response.Write("Hello world."); } }}
Running Http://localhost/XEngine/mycustom, you can see the browser output Hello world.
The MVC framework treats the class that implements the IController interface as a controller, sending the request to it according to the routing rules.
In the example above, we used the HttpContext property of RequestContext, which is used to get information about HTTP requests.
RequestContext There is also an attribute routedata, which is used to obtain information about the request route, such as the name of the controller and the action can be obtained in the following ways:
requestcontext.routedata.values["Controller"]. ToString ();
Requestcontext.routedata.values["Action"]. ToString ();
The controller implementing the IController interface is responsible for handling all aspects of the request, including generating a response to the client.
In the practical application we like scaffolding directly inherit System.Web.Mvc.Controller, this way we do not need to implement the Execute method to output the content, can be through the MVC framework action Results to solve the problem.
Let's start with an example of how the actionreslut we used to generate the response, such as
public ActionResult NativeOutput(){ return Redirect("~/Account/Login");}
The Action method does not directly use the response object, but instead returns an object of type ActionResult. The ActionResult class describes the type of response, such as returning a view or jumping to another page.
When the MVC framework receives an ActionResult object from an action method, the Executeresult method of that object is called.
namespace System.Web.Mvc{ // 摘要: // 表示操作方法的结果。 public abstract class ActionResult { // 摘要: // 初始化 System.Web.Mvc.ActionResult 类的新实例。 protected ActionResult(); // 摘要: // 通过从 System.Web.Mvc.ActionResult 类继承的自定义类型,启用对操作方法结果的处理。 // // 参数: // context: // 用于执行结果的上下文。上下文信息包括控制器、HTTP 内容、请求上下文和路由数据。 public abstract void ExecuteResult(ControllerContext context); }}
We demonstrate the mechanism through a custom actionresult implementation, simulating this simple jump function, the Executeresult implementation is as follows:
namespace XEngine.Web.Utility{ public class CustomRedirectResult:ActionResult { public string Url { get; set; } public override void ExecuteResult(ControllerContext context) { string fullUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext); context.HttpContext.Response.Redirect(fullUrl); } }}
Use in Controller
public CustomRedirectResult CustomOutput(){ return new CustomRedirectResult { Url = "~/Account/Login" }; }
As you can see, the same effect is achieved.
Built-in action result type
The CUSTOMREDIRECTRESULT,MVC framework, similar to our implementation, contains some built-in action result types, all of which inherit from the Actionreslut type. such as the following list:
Https://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult.aspx
We can explicitly indicate the return type when we use it specifically, such as
public ViewResult xxx(){ xxx }
or unified return ActionResult, such as
public ActionResult xxx(){ xxx }
Generally I am general return ActionResult, this is more convenient. (In addition, an action may return different kinds of actionresult depending on the situation, and there is no way to explicitly return the type)
The above table, Httpstatuscoderesult, Httpunauthorizedresult, Emptyresult, the three action result is not a helper method.
Similar to our custom customredirectresult, the use of literals is used to explicitly return results. Let's look at the example below:
You can use the Httpstatuscoderesult class to send a specific HTTP status code to the browser. Take a look at the Httpstatuscoderesult example and return a specific HTTP result code:
This class does not have a specific controller helper method, so this class must be instantiated.
public HttpStatusCodeResult StatusCode(){ return new HttpStatusCodeResult(404, "URL cannot beserviced");}
401 and 404 are the two exceptions to Httpstatuscoderesult:
You can use the Httpnotfoundresult class to get the 404 effect above
public HttpStatusCodeResult NotFoundStatusCode(){ return HttpNotFound();}
Sends 401 results, usually redirects the user to the authentication page
public HttpStatusCodeResult UnauthorizedStatusCode(){ return new HttpUnauthorizedResult();}
As you can see, jump to the certification page after running
How data is delivered
Let's talk about the next topic: How to pass data in MVC. (Traditional session, the way the cookie is transferred can continue to use, it is no longer introduced)
The data transfer we use mainly has view to controller, controller to view, three kinds of data passing across view. Let's explain them separately.
First, controller receives view data
The Controller often needs to access data from input requests, such as query string values, form values, and the parameters that the routing system resolves based on the input URL. There are two main ways to access this data:
1. Through the context (similar to the prior version of ASP, such as our familiar request)
2. Through parameters of the action method (including model bindings), (the MVC framework automatically checks the context to assign values to these parameters)
These two methods are very common, we will explain in turn.
Get data through the context
When we create a controller by inheriting the Controllerbase class, we can take advantage of a set of properties of the context object to obtain information about the request, such as requests, Response, Routedata, HttpContext and server.
Commonly used to summarize the following table:
Some of the previous articles have been introduced, the other in the use of the introduction, will not repeat the explanation.
Through the parameters of the action method (using model binding)
The method of using parameters is more readable.
As the following rewrite example, we first use the context to read the form value, and then change to read as a parameter.
First define a view
@{ Layout = null;}<!DOCTYPE html>
Read through the context
public ActionResult GetDataFromView(){ ViewBag.Name = Request.Form["name"]; return View();}
Changed to read by parameter
public ActionResult GetDataFromView(string name){ ViewBag.Name = name; return View();}
After clicking the button, the following pages are returned:
By automatically examining context objects and properties, the MVC Framework provides values for the action method parameter, including Request.QueryString, Request.Form, and Routedata.values
Model bindings are the recommended way for MVC, and personal feelings can make the code cleaner. The principle is through value Provider? Model Binder of two components.
There is a set of built-in value Provider that fetch data items for Request.Form, Request.QueryString, Request.Files, and Routedata.values, and then pass those values to the model Binder, which attempts to map this data to the data type of the action method parameter.
Of course the parameter can also be a model, this way the previous article has been used many times, no longer repeat the example.
Second, the controller transmits the data to the viewSimply use the object as the view parameter (that is, pass a view model object).
public ActionResult DateOutput(){ DateTime date = DateTime.Now; return View(date);}
在View中使用Model关键字来访问@{ ViewBag.Title = "Index";}
This view is a no-type view. The view does not know anything about the view model, but treats it as an instance of object.
You can define the model type by creating a strongly typed view that contains details about the type of the view model object in the strongly typed views.
@model DateTime@{ ViewBag.Title = "Index";}
Note: Specifies that the model type is a lowercase m, which is read with an uppercase M
Using ViewBagIt has been used many times before, not to repeat it.
Personally, one of the great advantages of viewbag is that it facilitates sending multiple objects to a view.
Third, cross-request deliveryThe first two requests are in a round of request responses.
There is also a cross-request scenario, such as redirection, which causes the browser to submit a new HTTP request.
If you need to pass one of the requested data to the next request, you can use TempData.
You can use the same syntax as the session directly.
The difference between the TempData and the session is that when the TempData value is read, the value is marked for deletion.
When the request is finished, it is deleted.
There are two tips:
1, using the Peek method, you can get the value of tempdata, without marking it as delete
DateTime time = (DateTime)TempData.Peek("Date");
2, using the Keep method, you can retain a value that will be deleted
TempData.Keep("Date");
The Keep method does not permanently protect a value. If this value is read again, it will be marked for deletion again.
SummarizeThe controller needs to understand the common types of actionresult and how to master the data transfer.
Welcome all comments, wish the study progress:)
MVC 5 + EF6 Complete Tutorial 16--Controller details