用于将路由值作为链接的一部分传递的 TagHelper

在链接上指定 asp-controllerasp-action时,同时传递 id 属性的语法是什么?

例如。例如,如果我想链接到给定对象的编辑 URL,所需的 URL 应该是 /user/edit/5

是否有使用 TagHelpers 实现这一点的方法,或者我们仍然必须回到 @Html.ActionLink()

68906 次浏览

You can use the attribute prefix asp-route- to prefix your route variable names.

Example: <a asp-action="Edit" asp-route-id="10" asp-route-foo="bar">Edit</a>

you can pass custom ID using below code:

<a asp-controller="User" asp-action="Edit" asp-route-id="@item.ID">Edit</a>

I'd like to suggest a combination of the other two answers, but with a bit of extra clarification.

You will use an attribute prefix asp-route-{name} where {name} is the name of the route parameter you want to use. In other words, if the number 5 in your route is passed into the controller as an ID value, you could have:

<a asp-controller="User" asp-action="Edit" asp-route-id="@item.ID">Edit</a>

or if the parameter you wanted to pass to the route was item.UserName then

<a asp-controller="User" asp-action="Edit" asp-route-username="@item.UserName">Edit</a>

And if you had both parameters then

<a asp-controller="User" asp-action="Edit" asp-route-id="@item.Id" asp-route-username="@item.UserName">Edit</a>

I would suggest one more way for Razor view to use model value using @Html.actionlink in jsp

var URLvalue='@Html.ActionLink("UserString", "action", new { routeValueName1 = "__value1__", routeValueName2="__value2__" }, htmlAttributes: new { @class = "btn btn-default", @role = "button" })'
.replace('__value1__', Model.somevalue).replace('__value2__',  Model.somevalue);

you can use URLvalue where ever you want to in jsp or jquery.