开发者

ViewResult or ActionResult | does it makes sense to use ViewResult if ActionResult is good for everything anyways?

In asp.net mvc there is ViewResult for returning a View and ActionResult for returning whatever you want, so is there som开发者_如何学JAVAe good reason why should I use ViewResult instead of ActionResult when I'm sure that I will return a View ?


ActionResult is the general base class that all the other results are derived from like ViewResult,JsonResult and so on.

This way you can return multiple types of results like JSON and XML from the same method.


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.


You should use ViewResult to make code more readable and find bugs easier, but there can be other benefits too.

Since I use POST-REDIRECT-GET pattern, I wrote some tests to check if every [HttpPost] method returns RedirectToRouteResult. If I define other type of result in [HttpPost] method, it automatically doesn't pass test. This prevents me from returning View(model) in post method.


If you want to do unit testing then change it in the controller from ActionResult to ViewResult. Then you will have the intellisense in your Test Controller and life is good.


I just accidentally got same question some days ago and google came to help quickly. Basically there is no performance issue here, it's coding issue if any.

This is a short but useful blog post: http://www.techiesblog.com/post/2862100163/viewresult-vs-actionresult-asp-net-mvc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜