【问题标题】:Url.Action for [FromRoute] parameters[FromRoute] 参数的 Url.Action
【发布时间】:2018-08-21 19:17:51
【问题描述】:

在 ASP.NET MVC Core 2.0 中,我有一个控制器操作

public async Task<IActionResult> Details([FromRoute] string bigId, string smallId)

我怎样才能获得一个视图的链接?

像这样使用Url.Action()

<a href="@Url.Action("Details", "MyController",
            new {  bigId = Model.BigId, smallId = Model.SmallId })">
  Details
</a>

生成href="/Mycontroller/Details?bigId=123&amp;smallId=456",但我需要它,如"/Mycontroller/Details/123?smallId=456"

【问题讨论】:

  • 试试($"Details", "MyController", {Model.BigId}, new { smallId = Model.SmallId })
  • 不,“方法'Action'没有重载需要4个参数”。下面看我的回答,方法需要用 HttpGet("...") 修饰
  • 很公平,我相信如果您实际上将方法命名为 GetDetails,您可能可以跳过装饰,因为 Web Api 技术会发现它是约定中的 GET(避风港)虽然经过测试,但在某处阅读过)
  • @VishalChhodwani 请停止在帖子中添加随机粗体格式,因为这绝对不会提高问题质量。
  • @CodeCaster 我不是在做随机粗体格式,我只是突出显示关键字,这些关键字对于更好的解决方案很重要。

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


【解决方案1】:

没关系,我找到了答案。

控制器中的方法需要用

修饰
[HttpGet("Details/{bigId}")]
public async Task<IActionResult> Details([FromRoute] string bigId, string smallId)

然后视图中的 Url.Action 生成正确的 href:"/Mycontroller/Details/123?smallId=456"

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多