【问题标题】:@Url.Action pass id segment of current url@Url.Action 传递当前 url 的 id 段
【发布时间】:2020-09-10 06:51:55
【问题描述】:

我正在 dotnet core 3.1 C# MVC 中开发应用程序。

我在 Startup.cs 文件中有这样的 URL 映射:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Index}/{id?}");
            });

有一个名为 Dashboard 的控制器和我有这样的 URL 的操作方法 Index。

<domain>/<controller>/<action>/<id>
http://localhost:57088/Dashboard/Index/03359edbae9543b5a1bc956e9282cfb6

在 Razor 页面中,每当我使用 @Url.Action 创建指向同一控制器和同一操作的链接时,它都会自动添加 URL 的 id 段。

@Url.Action("Index", "Dashboard");

然后它会像这样创建 URL:

http://localhost:57088/Dashboard/Index/03359edbae9543b5a1bc956e9282cfb6

但是当我使用 @Url.Action 创建 URL 到不同的控制器时,它不会添加 URL 的 id 段。

@Url.Action("DoSomething", "Photos");

然后它会像这样创建 URL:

http://localhost:57088/Photos/DoSomething

但是我怎样才能创建这样的 URL:

http://localhost:57088/Photos/DoSomething/03359edbae9543b5a1bc956e9282cfb6

如何将相同的 id 段添加到使用 @Url.Action 的不同控制器?

【问题讨论】:

  • 将适当的路由值传递给 Url.Action
  • @pinkfloydx33 能否提供代码示例?
  • Url.Action("Index", "Dashboard", new { id = TheId }) 您需要为 TheId 传递一个值,但您必须知道要在那里使用什么值。显然它不会是随机的,并且会与 something (当前模型) 有关

标签: c# razor .net-core asp.net-core-mvc


【解决方案1】:

IUrlHelper.Actionan overload,它接受一个包含路由值的匿名对象。您需要调用此重载并传递必要的信息以正确识别您的操作。

例如,假设您的 Id 存储在模型的 Guid 字段中:

public class MyModel
{
   public Guid Id { get; set; }
   // other properties
}

Url.Action 的调用可能如下所示:

@Url.Action("DoSomething", "Photos", new { id = Model.Id });

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 2016-05-29
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多