Asp.Net MVC Default View Selection
March 19th, 2009 RustyI have blogged NONE for a very long time. We’ve been crazy busy at Ockham Research building our killer apps.
I discovered something today that I thought might be of value if anyone is still checking this blog. In Asp.Net MVC, when you request a url, the route engine looks up the appropriate controller and action for the request. Assuming a match is found, the controller’s action is executed and your code is called therein. At the end of your action logic, you will typically render a view. You do this like so:
return View( "SignUp" );
Since a while back (Preview 2?), The Microsoft team allowed us to use convention and omit the name of the view
return View();
That was great! So much easier and aligned with the idea of letting consistent behavior reduce verbosity and repetition. One gotcha caught me today…
public ActionResult CalledAction()
{
if( someCondition) return SomeOtherAction();
}
public ActionResult SomeOtherAction()
{
return SomeOtherAction();
}
In that above snippet, the CalledAction has a condition where a different action’s behavior is desired. You can call RedirectToAction and cause a round trip but the code as written will not behave correctly. The "SomeOtherAction()" method will render the "CalledAction" view. Bummer. Somehow I thought there was a reflection map that was initialize on startup that would recognize where the call came from and select the view. Turns out the Route manager pre selects the default view when he calls the initial action.
If you want to do what I proposed above (some might argue that its not good practice), you have to explicitly name your view.
…
return SomeOtherAction( "SomeOtherAction" );
}