asp-route-* 中的奇怪行为
strange behaviour in asp-route-*
在 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"];
访问名字值,我可以通过RouteData.Values["id"];
访问id值,为什么它适用于id但不是对于任何其他自定义属性?
RouteData
将仅包含与 路由 相关的数据。这是什么数据取决于用于导航到您的操作的路线模板。
默认路由模板如下所示:{controller=Home}/{action=Index}/{id?}
。忽略默认值,模板就是这样的:{controller}/{action}/{id?}
.
因此路由模板中有 三个 个槽位:controller
、action
和一个可选的 id
。这些是您将能够在 RouteData.Values
中看到的值,因为这些值用于匹配路由模板。
当您查看标签助手生成的 URL 时,您也可以看到这一点。它应该看起来像这样:/Home/Edit/123?firstname=name
。 id
是路由的一部分,而 firstname
仅作为查询参数传递。
这也意味着您 可以 通过 HttpContext.Request.Query
访问 firstname
,其中包含已传递的查询参数。请注意 id
未包含在 中,因为它是作为路由数据而不是查询数据传递的。
现在,当您在控制器操作中使用 model binding 时,幸运的是您不需要进行这种区分。默认行为将允许您通过简单地将它们指定为操作方法的参数来获取路由参数和查询参数。使用模型绑定当然是访问这些值的推荐方法,使 RouteData.Values
和 Request.Query
成为相当低级的机制。
在 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"];
访问名字值,我可以通过RouteData.Values["id"];
访问id值,为什么它适用于id但不是对于任何其他自定义属性?
RouteData
将仅包含与 路由 相关的数据。这是什么数据取决于用于导航到您的操作的路线模板。
默认路由模板如下所示:{controller=Home}/{action=Index}/{id?}
。忽略默认值,模板就是这样的:{controller}/{action}/{id?}
.
因此路由模板中有 三个 个槽位:controller
、action
和一个可选的 id
。这些是您将能够在 RouteData.Values
中看到的值,因为这些值用于匹配路由模板。
当您查看标签助手生成的 URL 时,您也可以看到这一点。它应该看起来像这样:/Home/Edit/123?firstname=name
。 id
是路由的一部分,而 firstname
仅作为查询参数传递。
这也意味着您 可以 通过 HttpContext.Request.Query
访问 firstname
,其中包含已传递的查询参数。请注意 id
未包含在 中,因为它是作为路由数据而不是查询数据传递的。
现在,当您在控制器操作中使用 model binding 时,幸运的是您不需要进行这种区分。默认行为将允许您通过简单地将它们指定为操作方法的参数来获取路由参数和查询参数。使用模型绑定当然是访问这些值的推荐方法,使 RouteData.Values
和 Request.Query
成为相当低级的机制。