Asp. Net MVC-Controller And Action, asp. netmvc

Source: Internet
Author: User

Asp. Net MVC-Controller And Action, asp. netmvc

1. Understanding Controllers

1.1. What is a controller?

The Controller is A. NET class that includes necessary request processing. The controller role encapsulates the application logic. The controller is mainly responsible for processing requests, performing model operations, and selecting a view to present to the user.

Easy to understand: the IController interface must be implemented. The modifier must be public, abstract, generic, and the class name must end with the Controller.


In the MVC Framework, the Controller class must implement System. web. the IController interface in the Mvc namespace, as shown in, is a very simple interface. This interface has only one Execute method. When requesting this controller, the Execute method is called. You can create a controller class by implementing the IController interface.

1.2. Functions of Controllers

A. Each request for an application is processed by the Controller in an appropriate way, as long as it does not deviate from the View and Model) the region in charge.

B. Do not place the business or data storage logic in the Controller or create user interfaces.

1.3 create a controller that implements the IController Interface

Example: create a class that implements the Icontroller interface, read route data, and generate a data write response.

Create a class named MyFirstController In the Controllers folder, implement the IController interface, and add the following code


Run the application and navigate to/MyFirst in the address bar to view the output of the controller.

Create a class to implement the IController interface. The MVC Framework regards it as a controller and sends the request to it without any restrictions on how to process and respond to the request, this is a good example because it shows you the scalability of the MVC framework, but it is very difficult to compile a complex application in this way.


1.4 create a Controller that inherits from the Controller class

Using System. web. mvc. controller class you can derive your Controller, System. web. mvc. the Controller class is a class that most Web developers need to be familiar with and is used to provide support for request processing. The Controller provides the following three key features.

(1) Action Method: the Action of a controller is divided into multiple methods (not the only Execute () Method ). Each action method is exposed to different URLs and called by parameters extracted from the input request.

(2) Action Result: You can return an object describing the Action Result (for example, rendering a view or redirecting to a different URL or Action method ), then you can use this object to achieve your goal. This separation between specified results and execution simplifies unit testing.

(3) Filter: You can encapsulate reusable behaviors into filters and add features to the code, mark this behavior to one or more controllers or action methods.

Unless you have a very clear requirement in your mind, the best way to create a Controller is to derive from the Controller class, which is exactly how you add a Controller in Visual Studio, what Visual Studio does for you.

Create a class named MySecondController In the Controllers folder, inherit from the Controller class, add an action method TestAction, and write the following code to return an action result, finally, right-click the Action Method to add the corresponding view.


Run the application and navigate to/MySecond/TestAction. The browsing result is as follows:


As a derived class of the Controller class, the task is to implement the action method and obtain the required input to process the request and generate an appropriate response. The following describes how to receive and respond to data.

Ii. Data reception by the Controller

2.1 Data Source

A. query string value B, form data c, and Route Data

The controller needs to frequently access data from input requests, such as query strings, form data, and the value of parameters parsed by the routing system based on the input URL. There are three main methods to access the data.

(1) Extract from context object.

(2) Data formed by being passed as a parameter to the Action Method.

(3) explicitly call the Model Binding function of the framework.

Note: The parameter names are case-insensitive. For example, the results of Request ["Test"] and Request ["test"] are the same. For example:

View


Controller


2.2 get data through context object

When you create a Controller derived from the Controller base class, you can access a group of very convenient attributes, including: Request, Response, RouteData, HttpContext, Server, etc, each attribute contains different information about the request. In the Action method, you can use any Context object to access these attributes. For example:

Public ActionResult Index () {string userName = User. identity. name; string serverName = Server. machineName; string clientIP = Request. userHostAddress; DateTime dateStamp = HttpContext. timestamp; string oldProductName = Request. form ["OldName"]; string newProductName = Request. form ["NewName"]; ViewBag. message = "the IP address of the local machine is:" + clientIP; return View ();}

You can use VS smart sensing to enter this in the Action method to find the available context information.


2.3 use Action method parameters


2.3.1 use Action method parameters

Is the following method more elegant and easy to read than the above method? However, it should be noted that the Action method does not allow the ref or out parameters. Although the compilation will not report an error, an exception will be thrown during the runtime. As shown below.

The MySecond controller code is as follows:


The Index view code is as follows:


The running result is as follows:

 

2.3.2 understand parameter Object Instantiation

The Controller base class uses the MVC framework component called "Value Provider" and "Model Binder" to obtain the parameter values of Action methods. The value provider presents a set of available data items to the Controller. There is a value provider created in a group from Request.

M, Request. queryString, Request. files, RouteData. values obtains the data items, and these Values are passed to the model binder. The model binder attempts to map the data to the Data Type of the Action method parameter. The default model binding can create and populate any. NET type objects, including custom types and sets.

2.3.3 understand optional and required parameters

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

A. Value Type parameters must be assigned values. If you want this parameter to be the same as the reference type parameter, you can define it as int? For example, public ActionResult Index (int? Num). If there is no value, the null value is passed instead of an exception.

B. Parameters of the reference type are optional. To make it necessary (ensure that a non-null value is passed), add some code on the Action Method to reject null. For example, if the value is null, an ArgumentNullException exception is thrown.

2.3.4 specify the default parameter value

If you want to process requests that do not contain the action method parameters, but do not want to check the null value in the code or throw an exception, you can use the optional parameter feature of C. As follows:

public ActionResult Index()
    {
      string userName = User.Identity.Name;
      string serverName = Server.MachineName;
      string clientIP = Request.UserHostAddress;
      DateTime dateStamp = HttpContext.Timestamp;

      string oldProductName = Request.Form["OldName"];
      string newProductName = Request.Form["NewName"];

      ViewBag.Message = "The IP of this machine is:" + clientIP;
      return View();
    }

When defining a parameter, you can mark the parameter as optional by assigning values to the parameter. For example, the default value is provided for the query and page parameters in the appeal code. The MVC Framework tries to obtain values for these parameters through requests, but if no value is available, it will be replaced by the specified default value.

For the string type parameter query, note that the string type is the reference type, which means no null value needs to be checked. If the request is a specified query string, the Action method is called with the string "all. For int type parameters, note that int type is a value type. If there is no page value, the request will not cause an error. This method will be called with the default value "1.

Iii. Controller response to data

3.1 understand the Action Result)

Principle:

A. the MVC Framework receives the ActionResult object returned from the Action method, calls the ExecuteResult method defined in the ActionResult class, implements the ActionResult, processes the Response object for us, and generates relevant output.

B. the MVC framework has many built-in ActionResult types, which are derived from the ActionResult class. It is convenient for us to select a specific return type in the Action method, for example, to present to the 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 in. All these types are derived from ActionResult, and there are convenient helper methods in the Controller class. The following explains how to use these result types.

The MVC Framework supports the following output types: 1. view 2. text Data 3. XML data 4. JSON data 5. file or binary data 6. returned error and HTTP Codes 7. custom ActionResult 8. redirection



3.2. Return HTML through the rendering View

The most common response from the Action method is to generate HTML and send it to the browser. To generate HTML using the Action result, you need to create an instance that specifies the ViewResult class to be presented. We write the following code in the Home controller. The Code specifies the HomePage view.


When the MVC Framework calls the ExecuteResult of the ViewResult object, it starts to search for the specified View.

If 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 you cannot find it before, you can search for it in the following order:

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

If a View is found, the search is stopped and the View is displayed to the client.

Specify the displayed View by path)

This naming convention is very convenient and simple, but it limits some of the views we can present. To present a specific view, you can provide a clear path. The following is an example.


When a view is specified in this way, the specified path must start with "/" or "~ /"And contains the extension (for example,. aspx ). Of course, this is not recommended, because it is not conducive to program expansion and maintenance, This is a binding or coupling, against the MVC design philosophy, there can be other methods to achieve the same effect, for example: use the RedirectToAction () method.

View auxiliary Method

View (): returns the View with the same name as the Action.

View ("viewName"): Return to the ViewName View of this controller.

View ("~ /Views/othercontroller/viewname. cshtml ~ /Or start with/, but it is not recommended to do so, because you can call methods such as RedirectToAction.

View ("viewname", "layout"): When the View is displayed, a master page is changed.

3.3 pass data from Action Method to View)

Data transmission methods: 1. View Model 2. ViewData 3. ViewBag 4. TempData

3.3.1. Provide view Model Objects

Pass an object as a parameter of the View method to the View. For example:

Controller

public ViewResult Index2()
{
DateTime date = DateTime.Now;
return View(date);
}
View section, when adding a view, select the razor view engine.
[H]
ViewBag.Title = "Index2";
}
<h2>Index</h2>
The day is: @(((DateTime)Model).DayOfWeek)
The above view is a view without type or weak type. It does not know any information about the view model object, and treats it as an instance of the object object object. In order to get the value of DayOfWeek property, the instance of object object needs to be forced to datetime, which can achieve the effect, but make the view messy.
We can improve it by creating a strongly typed view, that is, to specify the type of view model object in view, just add code: @ model datetime, as shown below:
@model DateTime
[H]
ViewBag.Title = "Index2";
}
<h2>Index</h2>
The day is: @Model.DayOfWeek
The operation results are as follows:
It can be found that the use of strongly typed views not only makes the view neat, but also makes it easy for us to code because of the intelligent perception of attributes. As shown below:
3.3.2 use viewbag to transfer data
We have used the viewbag view package feature earlier, which allows you to define any property on a dynamic object and access it in the view. As follows:
Controller part
public ViewResult Index2()
{
ViewBag.Message = "Hello ViewBag!";
ViewBag.Date=DateTime.Now;
return View();
}
Part View
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
</head>
<body>
<div>
the message is:@ViewBag.message<br/>
the day is:@ViewBag.Date.DayOfWeek
</div>
</body>
</html>
The operation effect is as follows:
Compared with view model objects, viewbag has the advantage that it can easily send multiple objects to the view. If we are limited to the view model, then in order to achieve the same effect, we need to create a new type with two types: string and datetime. Dynamic objects allow you to enter any sequence of property and method calls in a view.
3.3.3 use viewdata to transfer data
Viewdata appeared in the version before mvc3. Its main function is similar to viewbag, but viewdata is implemented by using viewdatadictionary class instead of a dynamic type. Viewdatadictionary class is a collection of regular key / value pairs and accessed through viewdata property of controller class. Here is an example:
Controller part
public ViewResult Index2()
{
ViewData["message"] = "Hello ViewBag!";
ViewData["Date"]=DateTime.Now;
return View();
}
Part View
public class MySecondController : Controller
{
public ActionResult Index()
{
TempData["Message"] = "Hello TempData";
Tempdata ["data"] = "the value of tempdata can only be read once";
return View();
}
public ActionResult TempDataTest()
{
return View();
}
}
The running result is consistent with that of viewbag.
In the above code, we see that viewdata needs to perform type conversion on object objects. Now that viewbag is available, it is recommended to use viewbag, and try to use strong type view and view model.
3.3.4 use tempdata to transfer data
In the [3.4.4. Use tempdata to retain redirected data] section, the use of tempdata to transfer data will be introduced, which will not be introduced here.
3.4 execution redirection
The usual result of an action method is not to produce output directly, but to reset the user's browser to another URL of the wizard. In most cases, this URL is another action method of the application that generates the output you want the user to see.
The redirected action method does not produce any output, but simply causes the browser to request another URL. In MVC programs, output is usually directed to other action methods.
When redirection was performed, one of the two HTTP codes was sent to the browser.
(1) Send HTTP 302 status code, which represents temporary redirection. (common type)
(2) Send HTTP 301 status code to indicate permanent redirection. (use with caution)
The types of redirection are: 1. Redirection to text URL 2. Redirection to routing system URL 3. Redirection 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. Here is an example:
If the URL you want to reset is 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 URL redirected to routing system
The disadvantage of using redirect to text URL is that the URL is limited and must be updated when the route changes. Fortunately, we can use the routing system, and use the RedirectToRoute method to generate a valid URL. This method will create an instance of RedirectToRouteResult. As follows:
3.4.3 redirect to action method
Using the redirecttoaction method can gracefully redirect to an action method. This method is just a encapsulation of the redirecttoroute method, which allows you to specify the value of the action method and the controller without creating an anonymous type. As follows:
If you want to redirect to another controller, you need to provide a controller name such as:
Note: the incoming action parameters or controller parameters will not be verified before they are passed to the routing system, so make sure that the target controller and action method exist.
3.4.4 use 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 session. The difference is that tempdata will be marked for deletion after being read and removed when the request is processed. This is a perfect arrangement to keep short-term data throughout the redirection process. Here is an example:
First, add a mysecond controller, and add the corresponding view. The view engine is razor, and write the following code:
Mysecond controller code
public class MySecondController : Controller
{
public ActionResult Index()
{
TempData["Message"] = "Hello TempData";
Tempdata ["data"] = "the value of tempdata can only be read once";
return View();
}
public ActionResult TempDataTest()
{
return View();
}
}
Index view code
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
the Data is:@TempData["Data"]
</div>
</body>
</html>
Tempdatatest view code
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>TempDataTest</title>
</head>
<body>
<div>
the Data is:@TempData["Data"]<br/>
the Message is:@TempData["Message"]
</div>
</body>
</html>
The operation results 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 to verify that the values in tempdata can only be read once in different views.
The value in tempdata can only be read once in a request. If we want to read the value of tempdata but don't let it be deleted, we can use the tempdata. Peek ("data") method. If you want to keep the value in tempdata once, you can use tempdata. Keep ("data").
3.5. Return text data
Content method parameter description: text data sent, HTTP content type header of response, encoding format. The last two parameters can be ignored. When the MVC framework assumes that the data is HTML (content type is text / HTML), it will query an encoding format supported by the browser declaration.
3.6 return XML data
using LinqService;
using System.Xml.Linq;
public ContentResult GetXMLData()
{
List<Books> books = bll.GetListBooks();
XElement data = new XElement("BooksList", books.Select(e =>
{
return new XElement("Books",
new XAttribute("title", e.Title),
new XAttribute("author", e.Author),
new XAttribute("Price", e.Price.ToString()));
})
}
3.7. Return JSON data
public ActionResult JSON()
{
JsonResult json = new JsonResult();
Userinfo userinfo = new userinfo {id = 1, name = "Zhang San", age = 11};
List<UserInfo> list=new List<UserInfo>{
New userinfo {id = 1, name = "Zhang San", age = 11},
New userinfo {id = 1, name = "Zhang San", age = 11},
New userinfo {id = 1, name = "Zhang San", age = 11},
New userinfo {id = 1, name = "Zhang San", age = 11}
}
//json.Data = list;
//json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
//return json;
//return new JsonResult() { Data = list, JsonRequestBehavior=JsonRequestBehavior.AllowGet };
return Json(userinfo,JsonRequestBehavior.AllowGet);
}
JSON is a lightweight text-based format used to describe hierarchical data structure. JSON is an effective JavaScript code, which means it is supported by all mainstream browsers
Built in the MVC framework is the jsonresult class, which enables us to serialize. Net objects into JSON format. The JSON method allows you to create a result type that returns jsonresult
3.8 return files and binary data
public FileResult AnnualReport()
{
String filename = @ "D: \ C ා advanced programming. Doc";
string contentType = "application/doc";
String downloadname = "C ා advanced programming 2013. Doc";
return File(filename, contentType, downloadName);
}
If you do not know the specific MIME type, you can specify the contenttype as application / octet stream
Lfileresult is an abstract base class, which is a subclass of three implementations:
1. Filepathresult: directly send files under a path of the server to the browser
2. Filecontentresult: Send a binary data in memory to the browser
3. Filestreamresult: send the contents of the opened FileStream 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 has no corresponding controller helper method, so it must be instantiated directly, as shown below:
public HttpStatusCodeResult StatusCode()
{
return new HttpStatusCodeResult(404,"file not found");
}
Send 404 results
Another wrapper class for a specific HTTP status code is httpunauthorizeresult, which returns a 401 code to indicate an unauthorized request. As follows:
public HttpStatusCodeResult StatusCode()
{
return new HttpUnauthorizedResult();
}
Summary: in this paper, the controller and action method in MVC design mode are introduced in detail, starting from two ways of realizing self defined controller class, and then the data receiving and response series of the controller are introduced. The main sources of data receiving are query string value, form data and route data. The data response includes view, text data, XML data, JSON data, file or binary data, return error and HTTP codes, customized actionresult and redirection.

 
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.