在MVC 2暧昧的动作方法 [英] Ambiguous action methods in MVC 2
问题描述
我有一些问题在MVC 2暧昧的动作方法我试过落实这里找到解决方案:的 ASP.NET MVC暧昧的动作方法的,但是这只是给了我一个,因为它认为我试图调用该操作方法我的 <资源无法找到错误STRONG>不要 的要调用。我使用的RequiredRequestValueAttribute类是同一个确切的什么在其他问题的解决方案:
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.
推荐答案
该解决方案假定您必须绝对使用相同的URL不管你被编号或名称选择的,那你的路线设置为传递值从URL此方法。
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);
}
更新:据的微软。操作方法不能根据参数重载当他们与属性,如NonActionAttribute或AcceptVerbsAttribute消除歧义的行动方法可以被重载
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."
这篇关于在MVC 2暧昧的动作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!