leora
leora

Reputation: 196741

asp.net mvc with optional parameters and partial views

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?

Upvotes: 1

Views: 1467

Answers (1)

Iain Galloway
Iain Galloway

Reputation: 19200

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:-

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) { ... }

Upvotes: 4

Related Questions