Use specific return types in your ASP.NET MVC action methods

Wednesday, 1 July 2009 19:00 by bengtbe

When looking at ASP.NET MVC examples on the web almost all action methods return ActionResult, even methods that could return a specific subclass. Here is an example from the NerdDinner source code: 

public ActionResult Index(int? page)

{

    const int pageSize = 25;

 

    var upcoming = dinnerRepository.FindUpcomingDinners();

    var paginated = new PaginatedList<Dinner>(upcoming, page ?? 0, pageSize);

 

    return View(paginated);

}

This method always returns a ViewResult, still they declare the return type as the ActionResult base class. This practice often leads to test code like the following:

ViewResult result = controller.Index(0) as ViewResult;

Assert.IsNotNull(result, "Controller should return a ViewResult");

 
In NerdDinner they even have a whole test just to make sure that the result is a ViewResult:
 

[TestMethod]

public void IndexAction_Should_Return_View()

{

    // Arrange

    var controller = CreateDinnersControllerAs("robcon");

 

    // Act

    var result = controller.Index(0);

 

    // Assert

    Assert.IsInstanceOfType(result, typeof(ViewResult));

}

 
All this testing code are unnecessary, if you just let your action methods use specific return types, like shown below:
 

public ViewResult Index(int? page)

{

    const int pageSize = 25;

 

    var upcoming = dinnerRepository.FindUpcomingDinners();

    var paginated = new PaginatedList<Dinner>(upcoming, page ?? 0, pageSize);

 

    return View(paginated);

}

This also makes it immediately clear for people reading the code, what this action method returns.

The only time I would return ActionResult is when different paths of the action method returns different subclasses. In these cases, you should of course write tests that verify the return types of the different paths.

In the book Pro ASP.NET MVC Framework Steven Sanderson also recommends returning specific types. Take a look at the quote below:

"This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests."

BTW: This blog post is not meant to criticize the NerdDinner tutorial. It is a great free tutorial, and is probably one of the best ways to get introduced to the ASP.NET MVC framework :)

kick it on DotNetKicks.com

Shout it