MVC Controller Class Introduction

Source: Internet
Author: User
Tags http post

1. Controller class

I, controller must be a public class;

II, must end with controller;

III, inheriting the Controller base class or implementing the IController interface class;

IV, the class must contain several public methods that return values of ActionResult, which are called action in MVC;

2, controller execution process:

When the controller is Mvchandler selected, the next step is to select the appropriate action by Actioninvoker , in the controller, each action can define 0 to many parameters, Actioninvoker will be able to input the data of the action parameter according to the information from the current RouteValue and the client, and finally formally call the action method that was selected by the controller "parameter input is through model binding Binding) mechanism to fetch data from the RequestContext property, and to match or input the data into the parameters of the method. "The return value after action execution is usually the ActionResult class (its subclasses have viewresult used to return a view, Redirectresult is used to go to a different address, Contentresult is used to return a text content, Fileresult is used to return a binary file), after the controller gets the ActionResult class, it starts executing the Executeresult () method of the ActionResult class and returns the execution result to the client. At this time controller task OK.

3. In the controller execution there is also an action filter mechanism, divided into 4 categories:

Authorization Filter (Authorization filter)

Action Filters (Action filter)

Results filters (Result filter)

Exception filter (Exception filter)

If Actioninvoker cannot find the corresponding action available, the Handleunknownaction () method of the System.Web.Mvc.Controller class is executed by default, and in that class, The Handleunknownaction method defaults to the error message "HTTP404 cannot find a resource."

C # code
    1. Using System;
    2. Using System.Collections.Generic;
    3. Using System.Linq;
    4. Using System.Web;
    5. Using SYSTEM.WEB.MVC;
    6. Namespace Mvcdemo.controllers
    7. {
    8. [HandleError]
    9. public class Homecontroller:controller
    10. {
    11. Public ActionResult Index ()
    12. {
    13. viewdata["Message" = "Welcome to ASP. mvc!";
    14. return View ();
    15. }
    16. Public ActionResult About ()
    17. {
    18. return View ();
    19. }
    20. }
    21. }

ViewData represents a Dictionary object that can read the data set by the object in view (<%:viewdata["Message"]%> or using <%=html.encode (viewdata[" Message "])%>).

The view () method is a helper method from the controller base class that returns Viewresult inheritance ActionResult, if there are no parameters in the view, The first parameter of the page view that returns the name of this action method is the model data to be passed to view, whose type cannot be string, otherwise it will be treated as a view name.

Action Name Picker:

C # code
    1. public class homecontroller:controller{
    2. Requested URL: Http://localhost/Home/Index
    3. The return is/views/home/index.aspx
    4. Public ActionResult Index () {
    5. return view ();
    6. }
    7. }
    8. public class homecontroller:controller{
    9. Requested URL: Http://localhost/Home/Default
    10. The return is/views/home/default.aspx
    11. [ActionName ("Default")]
    12. Public ActionResult Index () {
    13. return view ();
    14. }
    15. }

Action Method Picker

C # code
    1. [Nonaction]
    2. Public ActionResult Index () {
    3. Reurn view ();
    4. }
    5. Private ActionResult Index () {
    6. Reurn view ();
    7. }

There are HttpGet, HttpPost, Httpdelete, httpput attributes, one for the action name, one for display, and one for operation. Because the HTML window cannot send the "delete" HTTP verb, if you want the action to provide a way to handle the delete action like the rest protocol, you can use the same window to allow only "delete" actions. You can use the HTML helper method of the Html.httpmethodoverride () method to simulate the behavior of the HTTP delete method, but the window is actually sent as an HTTP post.

ActionResult:

Description

1), the parameters in Viewresult specify the page name and the app's main page (MasterPage) name, and the page declaration contains the MasterPageFile property, the MasterPage in action is the main.

2), in the Partialviewresult class, the function is similar to the Viewresult class, but it cannot assign a value to the view masterpage, usually used in the case of a front-end AJAX application, and can be Ajax to get some of the content of the page.

3), Emptyresult, some actions do not need to return any data after execution, such as a page after the completion of the execution of a direct to other pages, the Emptyresult class will not execute any response to the client's program, so it will not return any data.

C # code
    1. Public ActionResult Empty () {
    2. return new Emptyresutl ();
    3. }
    4. Or
    5. Public Viod Empty () {
    6. Return
    7. }

4), Contentresult class can respond to the results of text content, and can respond to any specified text content, Content-type and text encoding.

C # code
    1. Public ActionResult Content () {
    2. String Strhtml= "";
    3. Return Content (strhtml);
    4. }
    5. Or
    6. public string Content () {
    7. String Strhtml= "";
    8. Retrun strhtml;
    9. }
    10. Shows that in MVC, the returned class is converted to a string output as long as the action returns not actionresult;

5), Fileresult, can respond to arbitrary file content, including binary format data, such as files, PDF documents, zip files, you can enter a byte array, file path, stream data, content-type, download file name parameters and will be returned to the client. Its three sub-categories:

Filepathresult: Responding to an entity file

Filecontentresult: Responds to the contents of a byte array

Filestreamresult: Responding to a stream data

C # code
    1. Public ActionResult GetFile () {
    2. byte[] filecontent = Getfilebytearrayfromdb ();
    3. Return File (filecontent, "Application/pdf", "yourreport.pdf");
    4. }

The Server.urlpathencode () method is required when the Chinese name is encoded

6), the purpose of the Javascriptresult class is to respond to the JavaScript program code to the browser,

7), the Jsonresult class can automatically convert any object's data series to JSON format return, Jsonresult class uses JavaScriptSerializer instance to complete JSON serialization operation, but if your object cannot be serialized, This process can happen unexpectedly, starting with jsonresult from MVC2.0 to avoid JSON hijacking attacks, set by default, any request returned in the Jsonresult class does not allow the Get method to get any JSON data from it.

C # code
    1. Public ActionResult JSON () {
    2. Return Json (New {id=1;name= "would"});
    3. }

If the content of the HttpPost method should be: {"id": 1, "name": "Will"} but the use of httpget is not obtained, and error, but if only using the Get method, the data cannot be cached by the browser, So you can get the JSON data from the Get method in the following ways

C # code
    1. Public ActionResult JSON () {
    2. Return Json (New {id=1;name= "would"},jsonrequestbehavior.allowget);
    3. }

8), Redirectresult main purpose is to perform redirects to other pages

9), Redirecttoroute,

A, auxiliary method redirecttoaction

Go to another action in the same controller

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return redirecttoaction ("Samplepage");
    3. }

Go to the specified action for the specified controller

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return redirecttoaction ("List", "Member");
    3. }

Go to Membercontroller's list Action, and add page this routevalue value

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return redirecttoaction ("List", "Member", new {page=3});
    3. }

B, Auxiliary method Redirecttoroute

Go to another action in the same controller

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return Redirecttoroute (New {action = "samplepage"});
    3. }

Go to the specified action for the specified controller

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return Redirecttoroute (New {controller= "Member", action= "List"});
    3. }

Go to Membercontroller's list Action, and add page this routevalue value

C # code
    1. Public ActionResult Redirecttoactionsample () {
    2. Return Redirecttoroute (New {controller= "Member", action= "List", page=3});
    3. }
Category:. NET MVC

MVC Controller Class Introduction

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.