Ambiguous action methods in MVC 2

有些话、适合烂在心里 提交于 2019-12-11 03:53:23

问题


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.


回答1:


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."



来源:https://stackoverflow.com/questions/5734216/ambiguous-action-methods-in-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!