15th Chapter Controller and action

Source: Internet
Author: User

----------------------------------------------

Note: 1. If a request does contain a value for a parameter but cannot be converted to the correct type, the framework passes the default value of the parameter type and "Modelstate"

The name of this parameter is registered as a validation error. Unless you check for validation errors in Modelstate, the request will still be processed when the user enters bad data

(Do not enter any data or enter default values for processing).

2. In reality, some MVC programmers define the results of each action method as ActionResult , even if he knows that the return is a more specific type. (Loose Sex)

----------------------------------------------

A controller : The domain that handles only the model and view responsibilities, not the transaction, data store logic, and does not generate a user interface.

Encapsulates application logic: handles input requests, executes operations on the domain model, and selects views that are rendered to the user.

The MVC framework determines the target controller by reading the Controller property values generated by the routing data.

The MVC framework helps users assign values to the arguments of an action method (which is case -insensitive to the processing of parameter names).

Theroutedata.values object is obtained by examining the request.querystring,request.formin the context.

Second,controller class three key features :

1. action Method : The behavior of the controller is implemented through multiple methods. Each method is exposed to a different URL and is called by the parameters of the input request.

2. Action result : You can return an object that describes the result of the action, and can cross the object for the purpose. ( render a view, redirect to a different URL, action method )

3. Filter : The reusable Behavior (authentication) can be encapsulated into a filter by placing a [Attribute] (annotation attribute) on the source code to label the controller or action method.

Third,controller derived class work :1. Implement the action method,2. Get the various inputs required,3. Process the request,4. Generate an appropriate response

1. Receive input : Access input data (query string value, form value), parameters (resolved by the routing system based on the URL entered).

Three ways: 1. Extract from a set of contextual objects (context objects).

2. Data formed as parameters (Parameters) are passed to the action method.

3. Explicitly invoke the framework's model binding feature.

(1) Capturing data through contextual objects (obtained in the Convenience property ):

Common context Objects

Property Type Describe
Request.QueryString NameValueCollection The get variable sent with the request
Request.Form NameValueCollection The POSTT variable sent with the request
Request.Cookies HttpCookieCollection Cookies sent by the browser with this request
Request.httpmethod String The HTTP method used for the request (GET, post 、... )
Request.headers NameValueCollection The entire HTTP header that is sent with the request
Request.url Url The requested URL
Request.userhostaddress String The IP address of the requested user
Routedata.route RouteBase The Routetable.routes entry selected for the request
Routedata.values RouteValueDictionary Current route parameters (extracted from URL or default value)
Httpcontext.application Httpapplicationstatebase Application State Library
Httpcontext.cache Cache Application Cache Library
Httpcontext.items Idictionary State Library of the current request
Httpcontextsession Httpsessionstatebase Visitor's Session State Library
User Iprincipal Authentication information for logged-in users
TempData Tempdatadictionary Temporary data items stored for the current user

Iv. using the action method parameters

1. Parameter Object Instantiation: The Controller base class uses an MVC framework component called the value Provider and model binder to get the parameter values of the action method.

The value provider fetches Request.Form, Request.QueryString, Request.Files, and routedata.values data items to the model binder,

The model binder attempts to map this data to the data type of the parameters of the action method.

2. Optional parameters and mandatory parameters: the MVC framework is called with a null value when the value of a reference type (String, object, and so on) is not found.

The MVC framework throws an exception when it cannot find the value of a value type (int, double, and so on) and does not invoke an action method.

Mandatory parameter: value type; optional parameter: reference type.

Value type processing: (1) Use default value; (2) nullable type (int?) DateTime?)

Reference type handling: null judgment, throw exception

Optional parameters can be used for literal types (types that do not need to be defined with the New keyword), including string, int, double, and so on.

V. action Results (ActionResult)

1. The action result system is a command pattern . Describes the scene, sending the object that performed the action.

The command pattern uses an object to represent and encapsulate all the information (object, method name, parameter value) that is required for the method that is subsequently called.

Forms an object that encapsulates the target method name, the object of the target method, the target method parameter, and executes a method.

   The receive ActionResult object, called the Excuteresult method, processes the response object, generating the output.

Built-in ActionResult type

Type Describe Method of the auxiliary device
ViewResult Returns the specified or default view template View
Partialviewresult Returns the specified or default partial view template Parititalview
Redirecttorouteresult Sends a HTTP301 (or 302) redirect to an action method or a specific route entry, generating a URL based on the routing configuration

Redirecttoaction

Redirecttoactionpermanent

Redirecttoroute

Redirecttoroutepermanent

Redirectresult To send HTTP301 (or 302) redirection to a specific URL

Redirect

Redirectpermanent

Httpunauthorizedresult Set the HTTP status code of the response to 401 (not authorized), raising the current authentication mechanism requiring the visitor to sign in None
Httpnotfoundrresult Returns an HTTP "404-Not Found" error Httpnotfound
Httpstatuscoderesult Returns a specified HTTP code None
Emptyresult I don't do anything. None

2. Redirect:

Redirect to literal url:redirect (temporary), redirectpermanent (permanent)

Redirect to Route Url:redirecttoroute (temporary), redirecttoroutepermanent (permanent)

Redirect to action method: Redirecttoaction (temporary), redirecttoactionpermanent (permanent)

(note) provides values for controllers and action methods that are not inspected until they are passed to the routing system. It is the responsibility of the user to ensure that the specified target is actually present.

post/redirect/get Mode : Receives a POST request, processes the request, and then redirects the browser (302) so that the URL of another get request is formed by the browser.

HTTP Code 302: temporary redirection. Most commonly used.

HTTP Code 301: Permanent Redirection. Instructs the HTTP code sink not to request the original URL again. (use with caution) (redirectpermanent)

3. Keep redirected data : Redirection causes the browser to submit a completely new HTTP request, losing access to the details of the original request. You can use the TempData feature.

(note) ViewBag cannot be used in a cross-request scenario.

TempData is similar to session data, except that the value of TempData is marked for deletion after it has been read, and is deleted after the request has been processed.

You can use TempData. Peek The ("Date") method waits until the value is not marked for deletion. With TempData. Keep ("Date") method, reserved until the next read.

If you want to store some data that is not deleted after the request has been processed, use the session data (note: The session will point to the server resource and will not be deleted until it expires).

  HTTP404: New Httpstatuscoderesult (404, "URL cannot be serviced") or (derived class) Httpnotfound ()

  HTTP401: new Httpunauthorizedresult ()

15th Chapter Controller and action

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.