ActionResult of. NET MVC

Source: Internet
Author: User

of. NET MVCActionResult

ActionResult is the parent class for all controler return values. All the results are packaged by ActionResult and sent to the client.

Inheritance structure
  • System. Object
      • System.Web.Mvc.ActionResult Span style= "font-family: ' Segoe UI ', ' Lucida Grande ', Verdana, Arial, Helvetica, Sans-serif; Letter-spacing:normal; line-height:17.5499992370605px; " >
        • System.web.mvc . Contentresult
        • system.web.mvc Emptyresult
        • system.web.mvc Fileresult
        • system.web.mvc Httpstatuscoderesult
        • system.web.mvc Javascriptresult
        • system.web.mvc Jsonresult
        • system.web.mvc Redirectresult
        • system.web.mvc Redirecttorouteresult
        • system.web.mvc Viewresultbase

The

can be divided into four categories from the basic structure. view class , text class , file class , and status code class .

View class returns results

Start with the view class that we are most familiar with. View () and Partialview () They return ViewResult and partialviewresultrespectively. From the first time we approached. NET MVC was in use. The function is to give the processed data to the view engine (if any) to render the view.

return value Help Methods Description
ViewResult
View
Render a Page view
Partialviewresult
Partialview
Renders a Web page view, but does not use layout pages

In general, the view we create for each action is a partial view that contains only a subset of the pages. View () after rendering the view, the results are embedded in the layout page, returning all of the pages, and Partialview () sends the results directly to the client after rendering is finished.

Text class returns results
return value Help Methods Description
Contentresult
Content
Returns a string literal in which the content format of the text can be specified by MIME
Jsonresult
Json
Serializes the data into JSON, which is then returned to the client
Javascriptresult
Javascript
Returns a string in JavaScript format
Content ()

There is no difference between using the content () method and directly returning a string string, except that you can specify the format of the returned content (XML or HTML) and character encoding .

  1. Public string Content ()
  2. {
  3. return " ; //Browser display Hellokitty
  4. }
  5. Public ActionResult Content2()
  6. {
  7. //return Content ("
  8. //Specifies the format and character encoding of the returned text
  9. return Content ("", "text/html",System. ) Text. Encoding. UTF8);
  10. }
  11. The effect is the same.
Json ()

Pass in an object of any type, and format it as JSON as possible. I've tried basically any type of object can be formatted, but for a file or a picture of something like that after formatting is just a lot of useless garbled.

Generally speaking,Dictionary This type of key-value pair will be converted to JS class ,List This class will be converted to JS array .

  1. class Student
  2. {
  3. Public string Name { get; Set ; }
  4. Public int Age { get; Set ; }
  5. }
  6. Public ActionResult JSON1()
  7. {
  8. var array = new List<Student> ();
  9. Array. ADD (new Student { Name = "xiaoming", age = c14>});
  10. Array. ADD (new Student { Name = "Xiao Li", age =
  11. return Json (array,jsonrequestbehavior. Allowget); //jsonrequestbehavior is used to specify whether get access is allowed, only post is allowed by default
  12. //Run Result: [{"Name": "Xiaoming", "Age": 12},{"name": "Xiao Li", "Age": []
  13. }
  14. Public ActionResult JSON2()
  15. {
  16. //You can also use anonymous inner classes to save data
  17. return Json (new { name = "Test", age = +, sex = "Boy." }, jsonrequestbehavior. Allowget);
  18. //Run Result: {"name": "Test", "age": +, "Sex": "Boy"}
  19. }
JavaScript ()

JavaScript () directly returns a JavaScript code string. The effect of JavaScript () is actually the same as content ( ), except that JavaScript () automatically specifies that the content of the returned text is application/ X-javascript.

  1. Public ActionResult JS()
  2. {
  3. return JavaScript ("alert ('" + DateTime. ) Now. tolongtimestring () + "')");
  4. }
  5. Public ActionResult JS2()
  6. {
  7. return Content ("alert ('" + DateTime. ) Now. tolongtimestring () + " ')", "Application/x-javascript");
  8. //This writing effect is exactly the same as above
  9. }
  10. /*
  11. <! DOCTYPE html>
  12. <meta charset= "UTF-8" >
  13. <script src= "Http://localhost:5695/home/js2" ></script>
  14. <!--can fill in the action's address directly in the script tag--
  15. <body></body>
  16. */
The file class returns the result

The method that can be used to return files in controler is only file (). File () can send files in a variety of forms, through file names , binary byte[], stream streams. The file type must also be indicated by MIME when sending.

  1. Public ActionResult FILE1()
  2. {
  3. System. IO. Stream fs = System. IO. File. OpenRead (@"test.png");
  4. return File (fs, @"image/png"); //Flow through the method
  5. }
  6. Public ActionResult FILE2()
  7. {
  8. return File (@"test.png", @"image/png"); //By the way the file name
  9. }
  10. Public ActionResult FILE3()
  11. {
  12. System. Drawing. Bitmap b = new System. Drawing. Bitmap (a ); //Create a blank picture
  13. System. IO. MemoryStream ms = new System. IO. MemoryStream ();
  14. b. Save (Ms, System. Drawing. Imaging. ImageFormat. Bmp);
  15. byte [] bytes = ms. GetBuffer ();
  16. return File (bytes, @"image/bmp"); //way of binary data
  17. }
  18. /*
  19. It is now possible to assign an address directly to an IMG tag for display
  20. */

Note: The returned file is not too large, otherwise it will cause memory overflow. If you want to download large files, it is best to return the file address directly.

Implement anti-theft chain

If you simply return a file, it is too much of a meaning. Return a file via the controller with respect to the file address directly to the user, we can do some processing, such as only allow logged users to view this image, or to add a watermark on the image.

  1. Public ActionResult FILE1()
  2. {
  3. if (HttpContext. User. Identity. IsAuthenticated)
  4. //If the user is logged in, the picture will be displayed
  5. return File (@"test.png", @"image/png");
  6. Else
  7. //Do not log in to display a picture of the anti-theft chain
  8. return File (@"test.png", @"image/png");
  9. }
Implementing the Verification code

It is returned to the client by dynamically generating a picture. Refer to my post. NET MVC Verification code for specific steps.

Status Code class returns results
return value Help Methods Description
Redirectresult
Redirect
Returns an HTTP 302 status code that causes the client browser to jump to the specified URL
Redirecttorouteresult
Redirecttoaction
Returns an HTTP 302 status code that causes the client browser to jump to the specified action
Redirecttorouteresult
Redirecttoroute
Jumps to the specified URL, depending on the routing API
Httpstatuscoderesult
(None)
Returns a specific HTTP status code and Description
Httpunauthorizedresult
(None)
Returns an HTTP 401 status code prompting the user not to log in
Httpnotfoundresult
Httpnotfound
Returns an HTTP 404 status code prompting the user to access a resource that does not exist
Emptyresult
(None)
Returns an HTTP 200 status code indicating that the request was successful, but that it does not contain any information

If the action Returns a result of null, Controler automatically replaces null with emptyresult.

ActionResult of. NET MVC

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.