【问题标题】:ASP.NET MVC pass parameter as part of urlASP.NET MVC 将参数作为 url 的一部分传递
【发布时间】:2017-05-04 15:40:08
【问题描述】:

我正在尝试在我的应用程序中创建好看的 url,但是当我使用以下构造时

@Url.Action("Edit", "Account", new { userId = user.Id })

我有下一个参考mysite.com/Account/Edit?userId=42

如何获取类似于mysite.com/Account/Edit/42 的网址?

【问题讨论】:

  • userId 更改为 id 然后它将到达您的默认路由 {controller}/{action}/{id}

标签: c# html asp.net-mvc hyperlink routing


【解决方案1】:

App_Start 文件夹下的项目中,您将有一个名为RouteConfig.cs 的文件,您可以在其中为您的应用程序指定自定义路由。

默认情况下,您将拥有以下内容

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

如果您执行Url.Action("Edit", "Account", new {id = user.Id}) 之类的操作会受到影响

如果您想适应您不想将userId 更改为id 的规则,那么您可以按如下方式创建一个:

  routes.MapRoute(
            name: "EditRule",
            url: "{controller}/{action}/{userId}",
            defaults: new { controller = "Edit", action = "Account", userId = UrlParameter.Optional }
        );

注意:自定义规则应出现在您的默认规则之前,否则默认规则将被命中

【讨论】:

    【解决方案2】:

    使用

    @Url.Action("Edit", "Account", new { Id = user.Id })

    如果您在**controller method****model logic** 中使用过userId,请将其更改为Id

    `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多