MVC Controller Detailed

Source: Internet
Author: User
Tags httpcontext

Original address: http://www.cnblogs.com/SeeYouBug/p/6441934.html#3628606

Directory

  • First, understand the controller
      • 1.1, what is the controller
      • 1.2, the role of the controller
      • 1.3. Create a controller that implements the IController interface
      • 1.4. Create controllers that inherit from the Controller class
  • Second, the controller to the data reception
      • 2.1. Data sources
      • 2.2. Get the data through the context object
      • 2.3. Using Action Method parameters
        • 2.3.1, using the action method parameter
        • 2.3.2, understanding Parameter Object instantiation
        • 2.3.3, understanding optional parameters and Required parameters
        • 2.3.4, specifying default parameter values
  • Third, the controller response to the data
      • 3.1. Understanding action Results (action result)
      • 3.2. Return HTML through render view
      • 3.3. Passing data from the action method to the view
        • 3.3.1, providing view model objects
        • 3.3.2, using ViewBag to pass data
        • 3.3.3, using ViewData to pass data
        • 3.3.4, using TempData to pass data
      • 3.4. Perform redirection
        • 3.4.1, redirect to text URL
        • 3.4.2, redirecting URLs to the routing system
        • 3.4.3, redirect to Action (action) method
        • 3.4.4, using TempData to retain redirected data
      • 3.5. Return text data
      • 3.6. Return XML data
      • 3.7. Return JSON data
      • 3.8. Returning files and binary data
      • 3.9. Return error and HTTP Codes
First, understand the controller 1.1, what is the controller

The controller is the one that contains the necessary processing requests. NET class, the role of the controller encapsulates the application logic, the controller is responsible for processing the request, implementing the operation of the model, and selecting the view to render to the user.

Simple understanding: implements the IController interface, the modifier must be public, cannot be abstract, cannot be generic, the class name must end with a controller.

In the MVC framework, the Controller class must implement the IController interface under the SYSTEM.WEB.MVC namespace, as shown in this is a very simple interface that has only one execute method that is called when the controller is requested. By implementing the IController interface, you can create a controller class.

1.2, the role of the controller

A, every request for an application is handled freely by the controller in the appropriate way, as long as it does not deviate from the area of view and model.

b, do not put the business or data storage logic into the controller, do not create a user interface.

1.3. Create a controller that implements the IController interface

Example: Create a class that implements the IController interface, read the routing data, and generate a data write response.

Create a class named Myfirstcontroller under the Controllers folder, implement the IController interface and add the following code

When you run the application and navigate to the /myfirstin the Address bar, you can see the output produced by this controller.

Creating a class by implementing the IController interface, the MVC framework treats it as a controller and sends the request to it, and there are no restrictions on how to handle and respond to requests, which is a good example because it shows you the extensibility of the MVC framework. But it is very difficult to write a complex application in this way.

1.4. Create controllers that inherit from the Controller class

With the System.Web.Mvc.Controller class you can derive your controller, the System.Web.Mvc.Controller class is a class that most Web developers need to be familiar with to provide support for request handling, and the controller provides the following three key features.

(1), action method: The behavior of a controller is decomposed into multiple methods (not only the Execute () method). Each action method is exposed to a different URL and is called by the parameters extracted from the input request.

(2), action result: You can return an object that describes the result of the action (for example, render a view, or redirect to a different URL or action method), and then use that object to achieve your purpose. This separation between the specified result and execution simplifies unit testing.

(3), filter: You can encapsulate the reusable behavior as a filter, and then label the behavior as one over multiple controllers or action methods by adding attributes to the code.

Unless you have a very specific need in your mind, the best way to create a controller is to derive it through the controllers class, which is exactly what Visual Studio does for you in Visual Studio.

Under the Controllers folder, create a class named Mysecondcontroller, inherit the controller class, add an action method Testaction and write the following code to return an action result, Finally, right-click inside the action method to add the corresponding view.

Run the application and navigate to the /mysecond/testaction browsing results as follows:

As a derived class of the Controller class, the job is to implement the action method, get the various inputs needed to process the request, and generate an appropriate response. The subsequent content will describe the receipt and response of the data.

Second, the controller to the data received 2.1, the data source

A, query string value B, form data c, routing data

The controller requires frequent access to data from input requests, such as query strings , form data , and the values of parameters that are parsed by the routing system based on the input URL. There are three main ways to access this data.

(1), extracted from the context object.

(2) data that is formed as parameters are passed to the action method.

(3), explicitly call the framework model binding function.

Note : The parameter name is case-insensitive, such as request["test" and request["test"] results are the same. Such as:

View section

Controller section

2.2. Get the data through the context object

When you create a controller that derives from the controllers base class, you have access to a set of very convenient properties that include: Request, Response, Routedata, HttpContext, Server, and so on. Each property contains information that asks for different aspects. In the action method, you can use any of the context objects to access these properties. For example:

1 public ActionResult Index () 2         {3             string userName = User.Identity.Name; 4             string serverName = Server.machin ename; 5             string clientip = request.userhostaddress; 6             DateTime datestamp = httpcontext.timestamp; 7  8             string Oldproductname = request.form["Oldname"]; 9             String newproductname = request.form["NewName"];10             one viewbag.message = "Native IP is:" + clientip;12             return View ();         

You can use vs IntelliSense to enter this in the action method . Find these available contextual information.

2.3. Using the action method parameter 2.3.1, using the action method parameter

Does the following approach be more elegant and readable than the above method? However, it is important to note that the action method is not allowed to have ref or out parameters, although the compilation will not error, but the runtime throws an exception. as shown below.

The Mysecond controller code is as follows:

The index View code is as follows:

The results of the operation are as follows:

2.3.2, understanding Parameter Object instantiation

The Controller base class uses the MVC framework component called the value Provider and model binder to get the parameter values of the action method. The value provider renders the collection of available data items to the controller. There is a set of built-in value providers from Request.for

M, Request.QueryString, Request.Files, routedata.values get data items, and then these values are passed to the model binder, and the model binder attempts to map the data to the data type of the action method parameter. The default model bindings are able to create and populate any. Net-type objects, including custom types and collections.

2.3.3, understanding optional parameters and Required parameters

If the MVC framework cannot find a value for a reference type parameter (such as String or object), the action method is still called, but a null value is used for the parameter, and an exception is thrown if the value of the value type parameter (for example: int or double) is not found, and the action method is not called.

A, a value type parameter is a value that must be assigned. If you want this parameter to be the same as a reference type parameter, you can define it as an int? such as: Public ActionResult Index (int? num), when there is still no value, no exception occurs, but a null value is passed.

b, the parameter of the reference type is optional. To make it necessary (to ensure that a non-empty value is passed), add some code on the action method to deny null. For example, when the value equals null, a ArgumentNullException exception is thrown.

2.3.4, specifying default parameter values

If you want to handle requests that do not contain action method arguments, but you do not want to check for null values or throw exceptions in your code, you can use the optional parameter attribute of C # instead. As shown below:

1 public  ActionResult List (string query = "All", int page = 1) 2         {3             //Here omit code n lines ... 4             return View (); 5         }

When defining parameters, you can mark parameters as optional by assigning values to them, such as the Appeal code, which provides default values for the query and page parameters. The MVC framework attempts to get values for these parameters by request, but if no value is available, the default value specified will be substituted.

For the string type parameter query, note that the string type is a reference type, which means that you do not need to check for null values. If the request is a specified query string, the action method is called with the string "all" . for the int type parameter, note that the int type is a value type, and the request does not cause an error when there is no page value, and the method is called with the default value of "1" .

Third, the controller response to the data 3.1, understand the action results (action result)

Principle:

A, the MVC framework receives the ActionResult object returned from the action method and invokes the Executeresult method defined within the ActionResult class to implement the ActionResult. The response object is processed for us and the associated output is generated.

B, the MVC framework contains many actionresult types, all derived from the ActionResult class, which allows us to select specific return types within the action method, such as to render to view, You can select Viewresult as the return value of the action method.

The MVC framework contains many built-in action result types as shown, all of which are derived from ActionResult, where there is a convenient helper method in the Controller class. The following explains how to use these result types.

The output types supported by the MVC Framework are: 1. Views 2. Text data 3.XML data 4.JSON data 5. File or binary data 6. Return error and HTTP Codes 7. Custom ActionResult 8. redirect

3.2. Return HTML through render view

The most common response from the action method is to generate HTML and send it to the browser, in order to generate HTML using the action results (ActionResult), you need to create an instance of the Viewresult class that specifies the view to render. We write the following code in the home controller. The homepage view is specified in the code.

When the MVC framework invokes the executeresult of the Viewresult object, it begins to search for the specified view.

Area is used, the search order is as follows:

1,/area/<areaname>/views/<controllername>/<viewname>.aspx

2,/area/<areaname>/views/<controllername>/<viewname>.ascx

3,/area/<areaname>/views/shared/<controllername>/<viewname>.aspx

4,/area/<areaname>/views/shared/<controllername>/<viewname>.ascx

5,/area/<areaname>/views/<controllername>/<viewname>.cshtml

6,/area/<areaname>/views/<controllername>/<viewname>.vbhtml

7,/area/<areaname>/views/shared/<controllername>/<viewname>.chtml

8,/area/<areaname>/views/shared/<controllername>/<viewname>.vbhtml

If no area is used or is not found in the front, the search order is as follows:

1,/views/<controllername>/<viewname>.aspx

2,/views/<controllername>/<viewname>.ascx

3,/views/shared/<controllername>/<viewname>.aspx

4,/views/shared/<controllername>/<viewname>.ascx

5,/views/<controllername>/<viewname>.cshtml

6,/views/<controllername>/<viewname>.vbhtml

7,/views/shared/<controllername>/<viewname>.chtml

8,/views/shared/<controllername>/<viewname>.vbhtml

As soon as one view is found, stop the search and start rendering the found view to the client.

To specify the rendered view by path (view)

This method of naming conventions is convenient and straightforward, but it restricts some of the views we can render. If you want to render a specific view that provides a clear path, here is an example.

When we specify a view in this way, the specified path must be either "/" or "~/" and include the extension (for example:. aspx). Of course, this is not recommended to use, because it is not conducive to the extension and maintenance of the program, which is a binding or coupling, contrary to MVC design ideas, there are other ways to achieve the same effect such as: Using the redirecttoaction () method.

View Helper method

View (): Returns to the view with the same name as the action.

View ("ViewName"): Returns to the ViewName view of this controller.

View ("~/views/othercontroller/viewname.cshtml"): This method must start with ~/or/, but it is not recommended because you can call methods such as Redirecttoaction.

View ("ViewName", "Layout"): When rendering this view, change to a master page.

3.3. Passing data from the action method to the view

Several ways to transfer data: 1. View model 2.ViewData 3.ViewBag 4.TempData

3.3.1, providing view model objects

Passes an object to the view as a parameter of the view method. For example:

Controller section

1 public ViewResult Index2 () 2 {3    DateTime date = datetime.now;4    return View (date); 5}

View section, when adding views, select the Razor view engine.

1 @{2     viewbag.title = "Index2"; 3} 4 

The view above is a view with no type or weak type, it does not know any information about the view model object, and it is treated as an instance of the object. In order to get the value of the DayOfWeek property, it is necessary to turn the instance of the object into DateTime, so that the effect can be achieved, but the view becomes cluttered.

We can improve by creating a strongly typed view, that is, specifying the type of the view model object in view, just Add code:@model DateTimeas follows:

1 @model DateTime2 @{3     

The results of the operation are as follows:

It can be found that using strongly typed views not only makes the view neat, but also facilitates coding because of the IntelliSense of attributes. As shown in the following:

3.3.2, using ViewBag to pass data

In the previous we have used the ViewBag View Package feature, which allows you to define arbitrary properties on a dynamic object and be able to access them within the view. As shown below:

Controller section

1 public  ViewResult Index2 () 2         {3             viewbag.message = "Hello viewbag!"; 4             viewbag.date=datetime.now;5             return View (); 6         }

View section

1 @{2     Layout = null; 3} 4  5 <! DOCTYPE html> 6  7 

The results are as follows:

ViewBag has the advantage of being able to send multiple objects to a view easily relative to the view model object. If we are restricted to use only the view model, then in order to achieve the same effect we need to create a new type of member with a string and a DateTime two type. Use dynamic objects to enter any sequence of properties and method calls in the view.

3.3.3, using ViewData to pass data

ViewData appears in the previous version of MVC3, and the main feature is similar to ViewBag, but ViewData is implemented using the Viewdatadictionary class instead of a dynamic type. The Viewdatadictionary class is a regular collection of key/value pairs and is accessed through the ViewData property of the controller class. The following example:

Controller section

1 public  ViewResult Index2 () 2         {3             viewdata["message"] = "Hello viewbag!"; 4             viewdata["Date"]=datetime.now;5             return View (); 6         }

View section

1 @{2     Layout = null; 3} 4  5 <! DOCTYPE html> 6  7 

The running result is consistent with the viewbag run result.

In the above code, we see that ViewData needs to type-convert object objects, and now with ViewBag, it is recommended to use ViewBag and use strongly-typed views and view models as much as possible.

3.3.4, using TempData to pass data

Passing data using TempData is described in the section "3.4.4, using TempData to retain redirected data," which is not described here.

3.4. Perform redirection

The usual result of an action method is not to produce the output directly, but instead to redirect the user's browser to another URL. In most cases, this URL is another action method for the application that generates the output that you want the user to see.

The redirected action method does not produce any output, just let the browser request a different URL again. In an MVC program, it is generally directed to other action methods to produce the output.

When the redirect is performed, one of the two HTTP codes is sent to the browser.

(1), send HTTP 302 status code, representing temporary redirection. (Common type)

(2), send HTTP 301 status code, indicates permanent redirection. (Use caution)

The types of redirection are: 1. Redirect to text URL 2. Redirect to the URL of the routing system 3. Redirect to Action method

3.4.1, redirect to text URL

The most basic way to redirect a browser is to call the redirect method, which returns an instance of the Redirectresult class. The following example:

If you want the URL to be reset to be represented as a string and passed as a parameter to the redirect method. The redirect method sends a temporary redirect. You can send a permanent redirect using the Redirectpermanent method. For example:

3.4.2, redirecting URLs to the routing system

The disadvantage of using redirection to a text URL is that the URL is qualified, and the URL must be updated when the route changes. Fortunately, we can use the routing system to generate a valid URL using the Redirecttoroute method, which creates an instance of Redirecttorouteresult. As shown below:

3.4.3, redirect to Action (action) method

Using the Redirecttoaction method can be gracefully redirected to an action method, which simply encapsulates the Redirecttoroute method, allowing you to specify the value of the action method and the controller without creating an anonymous type. As shown below:

If you want to redirect to another controller, you need to provide the name of a controller such as:

Note: Incoming action parameters or controller parameters are not validated until they are passed to the routing system, so ensure that the target controller and the action method are present.

3.4.4, using TempData to retain redirected data

Redirection causes the browser to submit the entire new HTTP request, which means that the details of the original request cannot be accessed. If you want to pass data from one request to the next, you can use the TempData () method.

TempData is similar to the session, except that TempData is flagged for deletion after being read and removed when the request is processed. This is a perfect arrangement for wanting to keep short-term data throughout the redirection process. The following example:

First add a Mysecond controller and add the corresponding view, the view engine is razor and write the following code:

Mysecond Controller Code

1 Public  class Mysecondcontroller:controller 2     {3 public         ActionResult Index () 4         {5             tempdata[" Message "] =" Hello tempdata "; 6             tempdata["Data"] = "TempData value can only be read once"; 7             return View (); 8         } 9 public         ActionResult tempdatatest () 10         {One             return View ();         }13     }14     

Index View Code

1 @{2     Layout = null; 3} 4  5 <! DOCTYPE html> 6  7 

Tempdatatest View Code

1 @{2     Layout = null; 3} 4  5 <! DOCTYPE html> 6  7 

The results of the operation are as follows:

Note: The value of tempdata["Message" is not read in index, but both index and tempdatatest read the value of tempdata["Data". This is done to verify that the values inside the TempData can be read only once in different views.

The value inside the TempData can only be read once in a single request. If we want to read the value of the tempdata but do not let it be deleted, you can use the Tempdata.peek ("Data") method. You can use Tempdata.keep ("Data") if you want to keep the value inside the TempData.

3.5. Return text data

The content method parameter description: The text data sent, the HTTP Content-type header of the response, the encoding format. The last two arguments can be ignored, and in the case of the MVC framework assuming that the data is HTML (content type text/html), it queries the encoding format supported by a browser declaration.

3.6. Return XML data
1 using Linqservice; 2 using System.Xml.Linq; 3 public Contentresult Getxmldata () 4 {5     list<books> Books = BLL. Getlistbooks (); 6     XElement data = new XElement ("Bookslist", books. Select (E = 7     {8        return new XElement ("Books", 9          new XAttribute ("title", E.title), ten          new XAttribute ( "Author", E.author), each          new XAttribute ("Price", E.price.tostring ())))     ; 13}
3.7. Return JSON data
1 public   ActionResult JSON () 2         {3             jsonresult json = new Jsonresult (); 4  5             UserInfo userinfo=new User info{id=1, name= "Zhang San", age=11}; 6  7             list<userinfo> list=new list<userinfo>{8                 new userinfo{id=1, name= "Zhang San", age=11}, 9                 New userinfo{id=1, name= "Zhang San", age=11},10                 new userinfo{id=1, name= "Zhang San", age=11},11                 new userinfo{id=1, Name= "Zhang Three ", age=11}12             };13             //json. Data = list;14             //json. Jsonrequestbehavior = jsonrequestbehavior.allowget;15             //return json;16             //return New Jsonresult () {Data = List, Jsonrequestbehavior=jsonrequestbehavior.allowget};17             return  Json (UserInfo, Jsonrequestbehavior.allowget);         

JSON is a lightweight text-based format used to describe hierarchical data structures, and JSON is a valid JavaScript code, which means that it is supported by all major browsers

The Jsonresult class is built into the MVC framework, allowing us to serialize. NET object is in JSON format. You can create a return jsonresult result type by using the JSON method

3.8. Returning files and binary data
1 public Fileresult Annualreport () 2 {3    string filename = @ "d:\c# advanced programming. Doc"; 4    string contentType = "application/ Doc "; 5    string downloadname =" C # advanced Programming 2013.doc "; 6    return File (filename, contentType, downloadname); 7}

If you do not know the specific MIME type, you can specify ContentType as Application/octet-stream

Lfileresult is an abstract base class with its three implementations of subclasses:

1.FilePathResult: Send a file directly to the browser from a path on the server

2.FileContentResult: Send a binary data in memory to the browser

3.FileStreamResult: Send the file stream content that has been opened to the browser.

3.9. Return error and HTTP Codes

Send a specific HTTP result code

You can use the Httpstatusresult class to send a specific HTTP status code to the browser. This class does not have a corresponding controller helper method, so you must instantiate the class directly, as follows:

1 public Httpstatuscoderesult StatusCode () 2 {3      return to new Httpstatuscoderesult (404, "File not Found"); 4}

Send 404 results

You can use the convenient Httpnotfoundresult class to get the same effect above, which is derived from Httpstatusresult and can be created using the controller's convenient method Httpnotfound. As shown below:

1 public  Httpstatuscoderesult StatusCode () 2 {3    return Httpnotfound (); 4}

Send 401 Results

Another wrapper class for a specific HTTP status code is Httpunauthorizeresult, which returns 401 code to indicate an unauthorized request. As shown below:

1 public  Httpstatuscoderesult StatusCode () 2  {3      return new Httpunauthorizedresult (); 4  }

Summary: in this article, mainly in the MVC design mode of the controller and the action method is described in detail, mainly from the implementation of the custom controller class two ways to start, and then introduced the controller to the data reception and response series content. The data receive main source query string value, form data, route data are introduced separately, the response to the data includes views, text data, XML data, JSON data, file or binary data, return error and HTTP Codes, custom ActionResult, Redirects were made separately introduced. Finally, some of the theoretical points of this article are quoted in the book "Pro ASP. NET MVC 5.pdf".

MVC Controller Detailed

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.