2

I'm having some problems with ambiguous action methods in MVC 2. I've tried implementing the solution found here: ASP.NET MVC ambiguous action methods, but that simply gives me a "The resource cannot be found" error as it thinks I'm trying to invoke the action method I don't want to invoke. The RequiredRequestValueAttribute class I'm using is the exact same one as what was in the other question's solution:

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
{
    public RequireRequestValueAttribute(string valueName)
    {
        ValueName = valueName;
    }
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return (controllerContext.HttpContext.Request[ValueName] != null);
    }
    public string ValueName { get; private set; }
}

My action methods are:

    //
    // GET: /Reviews/ShowReview/ID

    [RequireRequestValue("id")]
    public ActionResult ShowReview(int id)
    {
        var game = _gameRepository.GetGame(id);

        return View(game);
    }

    //
    // GET: /Reviews/ShowReview/Title

    [RequireRequestValue("title")]
    public ActionResult ShowReview(string title)
    {
        var game = _gameRepository.GetGame(title);

        return View(game);
    }

Right now, I'm trying to use the int id version, and instead it's invoking the string title version.

Community
  • 1
  • 1
Major Productions
  • 5,914
  • 13
  • 70
  • 149

1 Answers1

2

This solution assumes that you must absolutely use the same URL regardless of if you're selecting by ID or name, and that your route is set up to pass a value to this method from the URL.

[RequireRequestValue("gameIdentifier")]
public ActionResult ShowReview(string gameIdentifier)
{
    int gameId;
    Game game = null;
    var isInteger = Int32.TryParse(gameIdentifier, out gameId);

    if(isInteger)
    {
      game = _gameRepository.GetGame(gameId);
    }
    else
    {
      game = _gameRepository.GetGame(gameIdentifier);
    }

    return View(game);
}

Update: According to Microsoft: "Action methods cannot be overloaded based on parameters. Action methods can be overloaded when they are disambiguated with attributes such as NonActionAttribute or AcceptVerbsAttribute."

Peter J
  • 57,680
  • 8
  • 38
  • 45