为了使UrlHelper函数能够与动态路由一起工作,您需要在Startup.cs文件中进行一些更改,并使用Attribute Routing。
首先,在ConfigureServices方法中添加以下代码:
services.AddControllersWithViews(options => { // This option ensures that routes that contain parameters // can be used with the UrlHelper options.SuppressAsyncSuffixInActionNames = false; });
接下来,您需要在Configure方法中使用Attribute Routing进行路由。
例如,您的控制器可能是这样的:
[Route("[controller]")] public class MyController : Controller { [HttpGet("action/{id:int}")] public IActionResult MyAction(int id) { // Do something here } }
使用Attribute Routing后,您可以在视图中使用以下代码:
@Url.Action("MyAction", "My", new { id = Model.Id })
注意,"My"实际上是控制器的名称,使用Attribute Routing后您的控制器名称将成为路由中的最后一部分。
在上面的示例中,MyAction有一个参数id,因此我们可以在调用Url.Action时通过传递一个包含id的对象来指定该参数。
希望这个解决方法能够帮助您使UrlHelper函数能够与动态路由一起工作。