现在的位置: 首页 > 综合 > 正文

What’s the difference between ActionResult and ViewResult for action method?

2013年11月22日 ⁄ 综合 ⁄ 共 1579字 ⁄ 字号 评论关闭
 

ActionResult is an abstract class that can have several subtypes:

a) ViewResult - Renders a specifed view to the response stream

b) PartialViewResult - Renders a specifed partial view to the response stream

c) EmptyResult - An empty response is returned

d) RedirectResult - Performs an HTTP redirection to a specifed URL

e) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

f) JsonResult - Serializes a given ViewData object to JSON format

g) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

h) ContentResult - Writes content to the response stream without requiring a view

i) FileContentResult - Returns a fle to the client

j) FileStreamResult - Returns a fle to the client, which is provided by a Stream

k) FilePathResult - Returns a fle to the client

ActionResult is an abstract class.

ViewResult derives from ActionResult. Other derived classes includeJsonResult and
PartialViewResult.

You declare it this way so you can take advantage of polymorphism and return different types in the same method.

e.g:

public ActionResult Foo()
{
   if (someCondition)
     return View(); // returns ViewResult
   else
     return Json(); // returns JsonResult
}

ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could
change the method body to conditionally return a RedirectResult or something else without changing the method definition.

It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result

抱歉!评论已关闭.