Annoying untyped redirects in ASP.NET MVC

The .NET 3.5 is so powerful, you rarely need to use hardcoded strings now. But in ASP.NET MVC you still have to.

The sample that annoys me:

   1: public ActionResult LogIn(string username, string password) {
   2:     var user = EcoSpace.Query("User.allInstances->select(Username = un)")
   3:         .WithConstant("un", username)
   4:         .FromPersistence()
   5:         .AsList<User>()
   6:         .FirstOrDefault();
   7:  
   8:     if (user == null || !user.CheckPassword(password)) {
   9:         // Error
  10:         return View("Index");
  11:     } else {
  12:         // Ok.
  13:         return RedirectToAction("Index", "UserSummary")
  14:     }

See the lines 10 and 13. That's it. Hardcoded View name and Controller name.

I added an overload for RedirectToAction and it line 13 has changed to:

return RedirectToAction<UserSummaryController>(s => s.Index());

Ahh! Sweet.

Not sure yet what I can do with View method.

Here is the code snippet for RenderToAction:

   1: public RedirectToRouteResult RedirectToAction<TController>(Expression<Action<TController>> exp) where TController : Controller {
   2:     MethodCallExpression mce = exp.Body as MethodCallExpression;
   3:     if (mce == null)
   4:         throw new InvalidOperationException("Expression should represent a method call.");
   5:     var controllerName = mce.Object.Type.Name;
   6:     controllerName = controllerName.Substring(0, controllerName.Length - 10); // This is how it's done in ASP.NET :)
   7:  
   8:     RouteValueDictionary values = null; // Not supported yet
   9:     return RedirectToAction(mce.Method.Name, controllerName, values); 
  10: }

Enjoy.