【问题标题】:strange behaviour in asp-route-*asp-route-* 中的奇怪行为
【发布时间】:2019-08-25 13:29:28
【问题描述】:

在 index.cshtml 中我使用了一个锚标记助手

<a asp-action="Edit" asp-route-id="@Model.Id" asp-route-firstname="@Model.Name"</a>

在动作方法中

public IActionResult Edit(string id, string firstname)
{
   // id and firstname are assigned correct values
   // but  RouteData.Values only has three entries which are: controller, action and id, where is firstname?
}

但是我不能通过RouteData.Values["firstname"]; 访问firstname 值,我可以通过RouteData.Values["id"]; 访问id 值,为什么它适用于id 而不适用于任何其他自定义属性?

【问题讨论】:

    标签: c# asp.net-core-mvc tag-helpers


    【解决方案1】:

    RouteData 将只包含与路由相关的数据。这是什么数据取决于用于导航到您的操作的路由模板。

    默认路由模板如下所示:{controller=Home}/{action=Index}/{id?}。忽略默认值,模板就是这样:{controller}/{action}/{id?}

    所以路由模板中有三个槽:controlleraction,以及一个可选的id。这些是您将能够在RouteData.Values 中看到的值,因为这些值用于匹配路由模板。

    当您查看由标签助手生成的 URL 时,您也可以看到这一点。它应该看起来像这样:/Home/Edit/123?firstname=nameid 是路由的一部分,而 firstname 仅作为查询参数传递。

    这也意味着您可以通过 HttpContext.Request.Query 访问 firstname,其中包含传递的查询参数。请注意,id 包含在其中,因为它是作为路由数据而不是作为查询数据传递的。

    现在,当您在控制器操作中使用 model binding 时,幸运的是,您不需要进行这种区分。默认行为将允许您通过简单地将路由参数和查询参数指定为操作方法的参数来获取它们。使用模型绑定当然是访问这些值的推荐方式,这使得 RouteData.ValuesRequest.Query 的机制相当低级。

    【讨论】:

      猜你喜欢
      • 2016-05-15
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      相关资源
      最近更新 更多