Overloading Controller Methods in a MVC Project

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:

image

 

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:

image

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…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: