在我的桌子上有两个链接:
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Events", "LocationEvents", "Events", new {locationId = item.Id}, null)现在,我的目标是当我在链接上盘旋时,我希望url看起来像这样,两者都是这样的:
/Locations/Edit/4
/Events/LocationEvents/4不过,我明白这一点:
/Locations/Edit?id=4
/Events/LocationEvents/4这是我的RouteConfig.cs
routes.MapRoute(
name: "Events",
url: "{controller}/{action}/{locationId}",
defaults: new {controller = "Locations", action = "Index", locationId = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Locations", action = "Index", id = UrlParameter.Optional }
);我该怎么做呢?
发布于 2017-10-02 17:07:02
简单地说,你不能有两条这样的路线。它们在功能上都是相同的,采用控制器、动作和某种id值。id param名称不同这一事实不足以区分路线。
首先,您需要通过硬编码其中的一个参数来区分路线。例如,您可以这样做:
routes.MapRoute(
name: "Events",
url: "Events/{action}/{locationId}",
defaults: new {controller = "Locations", action = "Index", locationId = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Locations", action = "Index", id = UrlParameter.Optional }
);然后,第一条路径将只匹配以"Events“开头的URL。否则,将使用默认路由。当客户端请求URL时,这是正确处理路由所必需的。在生成路由方面,它仍然没有帮助您,因为UrlHelper没有足够的信息来确定选择哪一个路由。为此,您需要使用路由名称来显式地告诉它要使用哪一个:
@Html.RouteLink("Default", new { controller = "Edit", action = "edit", id = item.Id })坦率地说,RouteConfig风格的路由是一个巨大的痛苦。除非您所处理的结构非常简单,几乎可以由默认路由来处理,否则您最好使用属性路由,即描述每个操作应该具有的确切路由。例如:
[RoutePrefix("Events")]
public class EventsController : Controller
{
...
[Route("LocationEvents", Name = "LocationEvents")]
public ActionResult LocationEvents(int locationId)
{
...
}
}然后,它是绝对显式的,如果您想确保您得到了正确的路径,您只需使用名称(与Html.RouteLink、Url.RouteUrl等一起使用)。
https://stackoverflow.com/questions/46529103
复制相似问题