我正在重写这个问题,因为到目前为止的答案表明我对它的定义还不够好。我将把原来的问题留给下面的参考。
在设置路由时,您可以为不同的url/路由部分指定默认值。让我们考虑一下VS向导生成的示例:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "DefaultPage", action = "Index", id = UrlParameter.Optional } // Parameter defaults
在此示例中,如果未指定控制器,则将使用DefaultPageController,如果未指定操作,则将使用“索引”操作。urls通常如下所示:http://mysite/MyController/MyAction
。
如果Url中没有类似于:http://mysite/MyController
的操作,那么将使用索引操作。
现在让我们假设我的控制器索引和AnotherAction中有两个动作。对应的urls分别为http://mysite/MyController
和http://mysite/MyController/AnotherAction
。我的"Index“操作接受一个参数id。因此,如果我需要向索引操作传递一个参数,我可以这样做:http://mysite/MyController/Index/123
。请注意,与unlike不同,我必须显式指定http://mysite/MyController
操作。我想要做的是能够传递http://mysite/MyController/123
而不是http://mysite/MyController/Index/123
。我不需要这个网址中的“索引”,我希望mvc引擎能识别出,当我请求http://mysite/MyController/123
时,123不是一个动作(因为我还没有用这个名字定义一个动作),而是我默认动作“索引”的一个参数。我如何设置路由来实现这一点?
以下是问题的原文。
我有一个控制器,它有两个方法,定义如下
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(SomeFormData data)
{
return View();
}
这允许我像http://website/Page
一样处理Url,无论是当用户导航到这个url (GET)时,还是当他们随后回发表单时( post )。
现在,当我处理回帖时,在某些情况下,我想将浏览器重定向到这个url:
http://website/Page/123
其中123是某个整数,我需要一个方法在我的控制器中处理这个url。
如何设置路由,这样才能正常工作?目前我有向导生成的“默认”路由,如下所示:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "DefaultPage", action = "Index", id = UrlParameter.Optional } // Parameter defaults
我尝试添加另一个控制器方法,如下所示:
public ActionResult Index(int id)
{
return View();
}
但是当抛出不明确的动作异常时,这不起作用:
在以下操作方法之间,对控制器类型' PageController‘的操作’索引‘的当前请求不明确:类型PageController的类型PageController System.Web.Mvc.ActionResult索引(Int32)的System.Web.Mvc.ActionResult索引()
我必须补充的是,我在这个控制器中还有其他动作。如果我不这么做,This就能工作了。
发布于 2011-04-08 17:59:27
以下是如何解决此问题的方法:
您可以创建一个路由约束,以指示路由引擎,如果您的url中有类似数字(123)的内容,则这是默认操作的操作参数;如果您具有不像数字(AnotherAction)的内容,则它是一个操作。
考虑下面的代码:
routes.MapRoute(
"MyController", "MyController/{productId}",
new {controller="My", action="Index"},
new {productId = @"\d+" });
此路由定义将仅匹配http://mysite/MyController/123
中MyController之后的数值,因此它不会干扰对同一控制器上的另一个操作的调用。
发布于 2011-04-08 15:04:14
如果您将变量名保留为ID,则不需要更改任何内容。
将帖子重命名为"PostIndex“,并添加以下属性:
[ActionName("Index")]
SO here上也有同样的问题。
好的,这里有一个剪切/粘贴的答案,如果对你有帮助的话。
public ActionResult Index() {
return View();
}
[AcceptVerbs(HttpVerbs.Post), ActionName("Index")]
public ActionResult PostIndex(SomeFormData data) {
return View();
}
发布于 2011-04-08 16:36:26
哦,我明白了。我认为使用默认路由是不可能的,您需要映射自定义路由。
// /MyController/AnotherAction
routes.MapRoute(
null,
"MyController/AnotherAction",
new { controller = "DefaultPage", action = "AnotherAction" }
);
// /MyController
// /MyController/id
routes.MapRoute(
null,
"MyController/{id}",
new { controller = "DefaultPage", action = "Index", id = UrlParameter.Optional }
);
ps。最后必须映射/MyController/id之类的默认路由。
https://stackoverflow.com/questions/5591569
复制相似问题