gpt4 book ai didi

c# - 无法使 ActionLink 或 RouteLink 生成正确的 URL

转载 作者:行者123 更新时间:2023-11-30 20:09:20 26 4
gpt4 key购买 nike

我是 ASP.NET MVC(使用版本 3)的新手,无法让 ActionLinkRouteLink 像我期望的那样工作。在这个应用程序中,一个事件可以有很多事件,我希望使用以下方式路由到他们:

/Event/1/Activity/Event/1/Activity/Index  (same as previous)/Event/1/Activity/Details/5

The HTML generated by these two helpers always looks like:

/Event/1

Here's the code...

View Razor HTML

@Html.RouteLink("View Sessions", "SubControllerIndex",
new { eventId = Model.Id, controller = "Activity", action = "Index" })
@Html.ActionLink("View Sessions", "Index", "Activity", new { eventId = Model.Id }, null)

路由映射

routes.MapRoute(
"SubControllerIndex",
"Event/{eventId}/{controller}",
new { controller = "Activity", action = "Index" },
new { eventId = @"\d+" }
);
routes.MapRoute(
"ActivityIndex",
"Event/{eventId}/{controller}/{action}/{id}",
new { controller = "Activity", action = "Index", id = UrlParameter.Optional },
new { eventId = @"\d+", id = @"\d*" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { id = @"\d*" }
);

事件 Controller

public ActionResult Index(long eventId)
{
var activities = _context.Activities.Where(a => a.Event.Id == eventId).ToList();
return View(activities);
}

知道我在这里做错了什么吗?

最佳答案

路由系统为路由生成/Event/1而不是/Event/1/Activity/Index的原因

routes.MapRoute(
"ActivityIndex",
"Event/{eventId}/{controller}/{action}/{id}",
new { controller = "Activity", action = "Index", id = UrlParameter.Optional },
new { eventId = @"\d+", id = @"\d*" }
);

是因为在生成 url 时系统不会在 url 中包含任何默认值。在这种情况下,controller 的默认值是 Activity,action 的默认值是 Index。因此,

@Html.RouteLink("View Sessions", "SubControllerIndex",
new { eventId = Model.Id, controller = "Activity", action = "Index" })

将生成 /Event/1 而不是 /Event/1/Activity/Index。如果您单击该链接,您仍然应该转到 ActivityController 上的 Index 操作方法。

关于c# - 无法使 ActionLink 或 RouteLink 生成正确的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com