ASP. Mvc5 Step by Step (iv)--About controller ActionResult

Source: Internet
Author: User
Tags httpcontext

ActionResult is the result type returned after the Controller method executes, the Controller method can return a type that inherits directly or indirectly from the ActionResult abstract class, if the returned non-actionresult type, The controller will convert the result to a contentresult type. The default Controlleractioninvoker calls the Actionresult.executeresult method to generate the answer result.

First, ActionResult derived diagram:

Second, several common ActionResult

1,Contentresult

Returns simple plain text content that specifies the type of answer document through the ContentType property, and specifies the character encoding of the answer document through the ContentEncoding property. The Contentresult object is easily returned by the content method in the Controller class. If the Controller method returns a non-ActionResult object, MVC will simply produce a Contentresult object based on the ToString () content of the returned object.

C # codeCopy
PublicContentresult RssFeed (){story[] Stories=Getallstories ();//Fetch them from the database or wherever//Build the RSS feed document StringEncoding=Response.ContentEncoding.WebName; XDocument RSS= NewXDocument (NewXdeclaration ("1.0", Encoding,"Yes"),NewXElement ("Rss",NewXAttribute ("Version","2.0"),NewXElement ("Channel",NewXElement ("Title","Example RSS 2.0 Feed") from the storyInchStories SelectNewXElement ("Item",NewXElement ("title, story. Title), new XElement ( " description, story. Description), new XElement (  "link" , story. (URL)))); return Content (RSS. ToString (),  "application/rss+xml "); }             


2,Emptyresult

Returns an empty result. If the Controller method returns a NULL,MVC, convert it to a Emptyresult object.


3,Redirectresult

Represents a connection jump, which is equivalent to the Response.Redirect method in ASP. The corresponding controller method is redirect.

C # codeCopy
Public Override voidExecuteresult (ControllerContext context){If(Context== Null){Throw NewArgumentNullException ("Context"); } If(Context. Ischildaction){throw new InvalidOperationException (mvcresources.redirectaction_ Cannotredirectinchildaction); } string Destinationurl = Urlhelper.generatecontenturl (URL, Context. HttpContext); Context. Controller.TempData.Keep (); Context. HttpContext.Response.Redirect (Destinationurl, false /* endresponse */              /span>    


4,Redirecttorouteresult

Also means a reverse, MVC generates a URL address based on the routing name or routing information (routevaluedictionary) we specify, and then calls Response.Redirect jumps. The corresponding controller methods are redirecttoaction and Redirecttoroute.


5,ViewResult:

Represents a view result that produces an answer based on a view template. The corresponding Controller method is view.


6,Partialviewresult:

Represents a partial view result, which is essentially consistent with viewresult, except that the partial view does not support the master, which corresponds to asp.net,viewresult equivalent to a page, while Partialviewresult is equivalent to a UserControl. It corresponds to a controller method of Partialview.


7,Httpunauthorizedresult:

Represents an unauthorized access error. MVC sends a 401 response state to the client. If form validation (authentication mode= "forms") is turned on in Web. config, the 401 status shifts the URL to the specified loginurl link.


8,Javascriptresult:

is essentially a textual content, just set Response.ContentType to Application/x-javascript, This result should be used in conjunction with the Microsoftmvcajax.js script, after the client receives an AJAX response, it will determine the Response.ContentType value, if it is application/x-javascript, The return response is executed directly by Eval. The Controller method corresponding to this result type is JavaScript.


9,Jsonresult:

Represents a JSON result. MVC sets Response.ContentType to Application/json and serializes the specified objects into JSON representations through the JavaScriptSerializer class. It is important to note that MVC does not allow GET requests to return JSON results by default, to remove this restriction, and to set its Jsonrequestbehavior property to Jsonrequestbehavior.allowget when generating a Jsonresult object. The Controller method corresponding to this result is JSON.

C # codeCopy
ClassCitydata{Public StringCityPublic Inttemperature; } PublicJsonresult Weatherdata (){var Citiesarray= New[]{NewCitydata{City= "London", temperature= 68}new Citydata {City = hong kong" , temperature = 84< Span style= "color: #000000;" >}}; return Json (Citiesarray);}               /span>          


10,Filepathresult, Filecontentresult, Filestreamresult: These three classes inherit from the Fileresult, representing a file content, the difference between the three is that, FilePath transfers files to the client through a path, filecontent through binary data, and FileStream is transmitted by stream. The controller provides an overloaded method named file for the three file result types.

Filepathresult: Send a file directly to the client

C # codeCopy
Publicfilepathresult Downloadreport () { string filename = @ "c:\\files\\somefile. PDF"; return File (filename, "application/pdf", "annualreport"). PDF");} 

Filecontentresult: Returns a byte byte to the client than the slice

C # codeCopy
PublicFilecontentresult GetImage (IntPRODUCTID){var product=ProductsRepository.Products.First (x=X.productid== productId); return File (product. ImageData, product. Imagemimetype); }<img Src= " "getimage   "products" , new { Model.productid})%> "/>        

Filestreamresult: Return stream

C # codeCopy

 public     Filestreamresult proxyexampledotcom () { WebClient WC = new WebClient (); Stream stream = WC. OpenRead (http://www. Studyofnet . Com/); return File (stream, text/html ");} 

Third, the Controller's helper method, you can return the corresponding ActionResult

ASP. Mvc5 Step by Step (iv)--About controller ActionResult

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.