Overloading Controller Methods in a MVC Project
May 10, 2011 Leave a comment
I cranked up a new MVC3 project (Razor and Unit Testing). I went to the Home controller and added an overloaded method to the Index:
public ActionResult Index(string userName) { ViewBag.Message = String.Format("Welcome to ASP.NET MVC, {0}!", userName); return View(); }
I then hit F5 and got the following error:
I tried adding a route:
routes.MapRoute( "HomeIndexWithString", "Home/Index/{userName}", new { controller = "Home", action = "Index", userName = "" } );
and being explicit with the URL but I got the same error:
I then looked on Stack Overflow and added the ActionName attribute to my overloaded method:
[ActionName("HomeIndexWithString")] public ActionResult Index(string userName) { ViewBag.Message = String.Format("Welcome to ASP.NET MVC, {0}!", userName); return View(); }
The Index page returned, but the problem is that even when I passed in the explicit url, it still returned the default page. I then went back to the overloaded method and deleted it. I then added an optional parameter to the original index method and handled it if the value was populated:
public ActionResult Index(string? userName) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Welcome to ASP.NET MVC"); if (userName != null) { stringBuilder.Append(String.Format(", {0}!", userName)); } ViewBag.Message = stringBuilder.ToString(); return View(); }
The problem is that the compiler complains:
Error 1 The type ‘string’ must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method ‘System.Nullable<T>’
So I am down to creating a custom ActionMethodSelectAttribute that can handle the requests and parse appropriately. Since this smells like a kludge, I went back to the way MSFT wants me to do it – create a different method for each action and return to appropriate view. Naming confusion notwithstanding, I guess that is what I will do…