[ASP.]09-controller and Action (1)

Source: Internet
Author: User

[ASP.
MVC Calf Road]09-controller and Action (1)

We know that in MVC each request is submitted to the Controller for processing. Controller is closely related to the request, it contains the logical processing of the request, can operate on the Model and choose View to render to the user, for business and Data logic code, as well as interfaces and auxiliary class library, etc. generally do not put into the Controller.

The Controller and the Action content is more, I divide it into two articles, may also divide into three articles. This article introduces the controller's implementation, controller's acquisition of state data, ActionResult, and the data transfer of the action, followed by the Controller factory, action Invoker And some of the more advanced features that are not yet well thought out or are being studied.

Directory of this document


Inherit IController interface

In the previous articles in this series, the controller we added is a generic class that inherits from the abstract class System.Web.Mvc.Controller (Note: Controller (or controller) and controller The class is two meaning in this article, please understand the context when reading this article. The Controller abstract class encapsulates a lot of useful functionality, so developers don't have to write their own repetitive, cumbersome processing code.

If you do not use the encapsulated Controller abstract class, we can also create our own controller by implementing the IController interface. There is only one Exctute method in the IController interface:

Public interface IController {     void Execute (RequestContext requestcontext);}

The Controller interface is an interface with a very simple structure under the SYSTEM.WEB.MVC namespace.

The Execute method is called when the request is sent to a controller class that implements the IController interface (the routing system can find the controller through the requested URL).

Let's create an empty MVC application, add a class that implements IController under the Controllers folder, and do some simple things like this:

Using system.web.mvc;using system.web.routing;namespace mvcapplication1.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));}}    

Run the application, the URL is positioned to/basic/index (you can change the Index to any other fragment name) and the result is as follows:

Implement the IController class, MVC will recognize it as a controller class, according to the controller name of the corresponding request to this class processing.

But for a slightly more complex application, the implementation of the IController interface is going to do a lot of work, and we seldom do that. Through this we have a better understanding of the controller's operation, all of the controller in the processing of requests from the Execute method begins.


Inherit Controller abstract class

MVC allows us to customize and extend freely, such as the above-mentioned you can implement the IController interface to create various processing of various types of requests and produce results. If you don't like the Action method or don't care about View, you can write a better, faster, more elegant controller to handle the request yourself. But as said before, the implementation of their own IController interface to do a lot of work, the most important is not through long-term practice testing, the robustness of the code is not guaranteed, generally do not recommend you do so. The System.Web.Mvc.Controller class of the MVC framework provides useful features to facilitate our processing of requests and the return of results.

inherits the controller class controller we've used it a lot of times and we've got some knowledge of it, which provides several key features:

Action method: A Controller whose behavior is divided into multiple methods , a method typically corresponds to a request, and the data passed through the request can be obtained through the method parameters.
ActionResult: You can return an object that describes the result of the action method execution, and the advantage is that you want to return a result to specify the corresponding return object, without caring how to execute and produce the result.
Filters: With C # attributes, the processing of one behavior, such as authorization and validation, is encapsulated to facilitate reuse between multiple Controller and Action methods.

So, if you're not having a special need or a busy egg, the best way to create a controller that meets your requirements is to inherit the controller abstract class. Since we've used many times before, there's no specific demonstration here, but let's take a look at its code structure.

Add a Controller,vs under the Controllers folder the structure of the class has been built for us, and if you like neatness, you will habitually delete the references that you do not need, and the code is as follows:

Using System.web.mvc;namespace mvcapplication1.controllers {public        class Derivedcontroller:controller {                Public ActionResult Index () {            viewbag.message = ' Hello from the Derivedcontroller index method ';            Return View ("MyView");}}}    

We can look at the definition of the Controller abstract class, discover that it inherits the Controllerbase class, implement the Execute method of the IController interface in the Controllerbase class, This method is the entry of the various components of the MVC process to the request, including the Action method that is found through the routing system and called.

The Controller class uses the Razor view system to render view, where the view method is used to specify the name parameter of the view to tell MVC to select MyView view to return to the user result.


Getting state data in the Controller

We often need access to data submitted by clients, such as QueryString values, form values, and parameter values from URLs through the routing system, which can all be referred to as state data. The following are the three main sources that get state data from a Controller:

A series of context objects.
The arguments passed to the Action method.
Explicitly invokes the model binding attribute of the framework.

Getting state data from a context object

The most straightforward way to get state data is to extract it from the context object. When you create a controller that inherits from the Controller class, you can easily access and request related data through a series of properties, including request, Response, Routedata, HttpContext, and Server, each of which provides different types of information related to the request. The most common context objects are listed below:


You can use any context object in the action method to get information about the request, as demonstrated in the action method below:

... public actionresult renameproduct () {    //Access different context object    string userName = User.Identity.Name;    string serverName = Server.machinename;    string clientip = request.userhostaddress;    DateTime datestamp = Httpcontext.timestamp;    Auditrequest (UserName, ServerName, ClientIP, Datestamp, "renaming product");                Get data from the form submitted by the POST request    string oldproductname = request.form["Oldname"];    String newproductname = request.form["NewName"];    BOOL result = Attemptproductrename (Oldproductname, newproductname);    viewdata["Renameresult"] = result;    Return View ("productrenamed");} ...

These upper and lower objects do not have to be deliberately written, and when used, you can use the smart hints of VS to understand these context objects.

Get state data using the Action method parameter

In the previous articles in this series, we have learned how to receive data through the Action parameter, which is more concise and straightforward than what is obtained from the context object above. For example, we have the following Action method that uses the context object:

Public ActionResult Showweatherforecast () {    String city = (string) routedata.values[' city '];    DateTime fordate = DateTime.Parse (request.form["fordate"]);    Do something     ... return View ();}

We can use the Action method parameter to override it as follows:

Public ActionResult Showweatherforecast (String city, DateTime fordate) {     //do something ...     return View (); }

It is not only easy to read, but also convenient for unit testing.

The arguments of the Action method do not allow the use of ref and out parameters, which is meaningless.

The MVC framework provides values for the parameters of the action method by examining the context object, whose name is case-insensitive, such as the value of the city parameter of the action method can be obtained by request.form["City").

Understand how the arguments to the Action method are assigned

The Controller class obtains the value of the parameter for the Action method through the value provider of the MVC framework and the model binder component.

Value provider provides a range of values that can be accessed in the controller, internally it passes from Request.Form, Request.QueryString, Request.Files, and Routedata.values Data (a collection of key values), and then passing the data to model Binder,model Binder attempts to match the data to the parameters of the action method. The default model binder can be created and assigned to any. NET type Object parameters (that is, the parameters of the Action method), including the collection and the custom type.

This is not an introduction to model binder, and I will introduce it specifically in the subsequent blog post of this series.


Understanding ActionResult

ActionResult is the object that describes the result of the action method execution, and the advantage is that you want to return what results to specify the corresponding return object, not to care about how to use the response object to organize and produce the results. ActionResult is an example of a command pattern that describes operations by storing and passing objects.

When the MVC framework receives an ActionResult object from the Action method, it calls the object's Executeresult method, which internally returns the output we want by Response object.

For a better understanding, we define a actionresult by inheriting the ActionResult class. Add a infrastructure folder to the MVC project, where you create a class file named Customredirectresult with the following code:

Using System.web.mvc;namespace mvcapplication1.infrastructure {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);}}}    

When we create an instance of the Customredirectresult class, we can pass the URL that we want to jump to. When the action method execution ends, the MVC framework calls the Executeresult method, the Executeresult method obtains the Response object through the ControllerContext object, and then calls the Redirect method.

Here we use the custom Customredirectresult in the Controller:

public class Derivedcontroller:controller {    ...    Public ActionResult Produceoutput () {        if (Server.machinename = = "Wl-pc") {            return new Customredirectresult {URL = "/basic/index"};        }        else {            Response.Write ("controller:derived, Action:produceoutput");            return null;        }    }

After running we see the following results:

Direct redirection to the specified/basic/index when running on native (WL-PC).

We can use the MVC framework to provide a way to implement redirects by customizing Customredirectresult, as follows:

... public actionresult produceoutput () {     return new Redirectresult ("/basic/index");}

For ease of use, the Controller class provides a simple method for most types of ActionResult, as the above can be abbreviated as follows:

... public actionresult produceoutput () {     return Redirect ("/basic/index");}

The MVC framework contains many actionresult types, all of which inherit from the ActionResult class, most of which have simple methods in the Controller class, some of which are listed below:

In addition to the table listed, there are Contentresult, Fileresult, Jsonresult and Javascriptresult. Specific usage of each type of actionresult here is not to say, you can see Mr. Jiang's understanding of ASP.
MVC several actionresult of the essential series of articles.


Several ways to pass data from an Action to a View

We often need to pass data to a View in the action method, and the MVC framework provides some handy operations for this. Here is a brief introduction to several common ways.

View Model Object

Passing data to view through the view model object is the most common way to pass the view model object to view through the view method at the end of the Acton method execution, as shown in the following code:

... public ViewResult Index () {     DateTime date = DateTime.Now;     return View (date); }

In view we use the Model property to pass the view model object, as follows:

@model DateTime @{     viewbag.title = "Index";} 

In the Razor view engine, the role of @model is to declare the type of the Odel property, eliminating the hassle of type conversion, and @Model is a reference to the V Iew model object.

ViewBag, ViewData, and TempData properties

ViewBag, ViewData, and TempData are all properties that can be accessed in the Controller and View, and are used to store small amounts of data, with the following differences:

ViewBag, which is a weak type of dynamic, is parsed when the program is run and is a new feature in MVC3, only valid in the current view.
ViewData, is a collection of dictionaries, is only valid in the current view, performance is higher than VIEWBAG, but the use of the need for type conversion.
TempData, also a dictionary collection, is typically used to temporarily cache content between two requests or to pass messages between pages, saved in the session, and then purged from the session after use.

Here are three examples of use, first in the Controller to store small data in three, respectively:

public class Derivedcontroller:controller {public    actionresult Index () {        Viewbag.dayofweek = DateTime.Now.DayOfWeek;        viewdata["DayOfMonth"] = DateTime.Now.Day;        return View ();    }    Public ActionResult Produceoutput () {        tempdata[' message '] = "Warning message from Derived Controller.";        Return Redirect ("/home/index");}    }

In the index.cshtml in the views/derived directory, remove the stored data from ViewBag and ViewData:

... Day's week from ViewBag: @ViewBag. Dayofweek<p/> Day of month from ViewData: @ViewData ["DayOfMonth"]

In the index.cshtml in the Views/home directory, take the data from the TempData as follows:

... @TempData ["Message"]

When/derived/produceoutput is requested, the Produceoutput method saves a message to TempData and jumps to/home/index.

The following are the results when you navigate URLs to/derived/index and/derived/produceoutput, respectively:

Typically use ViewBag or ViewData in the current View to pass temporary data between two requests with TempData. Since TempData is released after being used, it needs to be stored in other variables if you want to use the data in TempData two times.

The above is the content of the [ASP.]09-controller and Action (1), more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.