tags:

views:

264

answers:

1

i have:

AlbumsController PhotoRepository Index.aspx (view)

inside of Index.aspx, i have a partial view call AlbumControl. I want to update this via ajax and ajaxhelper.

the issue is that i want the ability to do the following:

http://www.mysite.com/Albums
http://www.mysite.com/Albums?FilterTag=Birthdays

when i do this, i get the following error:

The current request for action 'Index' on controller type 'AlbumsController' is ambiguous between the following action methods:

System.Web.Mvc.ActionResult Index(System.String) on type Controllers.AlbumsController System.Web.Mvc.ActionResult Index() on type Controllers.AlbumsController

i would have thought that asp.net mvc would have figured it out where if i pass in a parameter in the querystring it would go to the Index(string Tag) method and if i didn't pass in a parameter, it would go to Index().

suggestions?

+4  A: 

The problem is that the MVC Routing Engine can't tell the difference between:-

1) Calling Index()

and

2) Calling Index(string tag) with tag = null

That's why it says the request is ambiguous.

You can just do:-

public ActionResult Index(string tag)
{
  if(String.IsNullOrEmpty(tag))
  {
    // index code goes here
    return View("Index");
  }
  else
  {
    // code to handle filtered view goes here
    return View("Tag");
  }
}

or you can force the parameter to be required with a custom attribute:-

http://stackoverflow.com/questions/1045316/asp-net-mvc-ambiguous-action-methods

or you can set up routes so that Albums and Albums?FilterTag=X explicitly go to different actions (Incidentally, I'd recommend "Albums" and "Albums/X"):-

  routes.MapRoute("AlbumsIndex", "Albums",
    new { controller = "Albums", action = "Index" });
  routes.MapRoute("AlbumsTag", "Albums/{tag}",
    new { controller = "Albums", action = "Tag", tag = "" });
  routes.MapRoute("Default", "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" );

and

public ActionResult Index() { ... }
public ActionRestlt Tag(string tag) { ... }
Iain Galloway
Pretty much what I was going to type. Personally though, I would shoot more for the attribute side of it to either set the value to a default if not there or to redirect on error. Just makes it easier to avoid repeat code in case it's a parameter that comes up a lot.
Programmin Tool
Programmin Tool - what would be the attribute approach here?
ooo
Seeing as it's not something built into the route (IE has the ? and tag in the url), probably just check the filterContext.ActionParameters to see if it exists. If it doesn't, add it. If it does but is null, set a default parameter. That's only if you don't want to check for null in the actual method though. If you don't mind doing that, it's probably quicker to do the null string check example. I use attributes on things that I know will be used in a lot of places like setting pageNumber to 0 if it doesn't exist.
Programmin Tool