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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值