路由到有相同的名字但参数不同的操作 [英] Routing to the actions with same names but different parameters
问题描述
我有这一套路线:
routes.MapRoute(
"IssueType",
"issue/{type}",
new { controller = "Issue", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
下面是控制器类:
public class IssueController : Controller
{
public ActionResult Index()
{
// todo: redirect to concrete type
return View();
}
public ActionResult Index(string type)
{
return View();
}
}
为什么,当我要求的http://主机/问题我得到行动索引当前请求的控制器类型IssueController'是下面的操作方法之间模棱两可的:
结果
我期望在没有参数的第一个方法应该采取行动,并指定一些参数,当第二个。
why, when i request http://host/issue i get The current request for action 'Index' on controller type 'IssueController' is ambiguous between the following action methods:
I expect that first one method should act when there is no parameters, and second one when some parameter specified.
在哪里我犯的错误?
UPD :可能重复:<一href=\"http://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc\">http://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc
2 UPD :由于上面的链接 - 没有做出行动超载任何合法的方式,它是
UPD 2: due to the link above - there is no any legal way to make action overloading, is it?
UPD 3 :操作方法不能根据参数(三)已重载<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx\">http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx
UPD 3: Action methods cannot be overloaded based on parameters (c) http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx
推荐答案
我会看起来一个有效的类型变量
I would have one Index method that looks for a valid type variable
public class IssueController : Controller
{
public ActionResult Index(string type)
{
if(string.isNullOrEmpty(type)){
return View("viewWithOutType");}
else{
return View("viewWithType");}
}
}
编辑:
如何创建查找特定请求值在这个岗位<一个自定义属性href=\"http://stackoverflow.com/questions/1045316/asp-net-mvc-ambiguous-action-methods\">StackOverflow
How about creating a custom attribute that looks for a specific request value as in this post StackOverflow
[RequireRequestValue("someInt")]
public ActionResult MyMethod(int someInt) { /* ... */ }
[RequireRequestValue("someString")]
public ActionResult MyMethod(string someString) { /* ... */ }
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; }
}
这篇关于路由到有相同的名字但参数不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!