When specifying asp-controller
and asp-action
on a link, what's the syntax for also passing an id attribute?
E.g. If I wanted to link to the edit URL for a given object, the required URL would be /user/edit/5
for example.
Is there a method to achieve this using TagHelpers, or do we still have to fall back to @Html.ActionLink()
?
The asp-all-route-data attribute supports the creation of a dictionary of key-value pairs. The key is the parameter name, and the value is the parameter value. In the following example, a dictionary is initialized and passed to a Razor view. Alternatively, the data could be passed in with your model.
In this section, we will learn each attribute that can be used with Anchor Tag Helper. It is used to associate the Controller name that is used to generate the URL. The Controller that is specified here must exist in the current project.
Route values are the values extracted from a URL based on a given route template. Each route parameter in a template will have an associated route value and is stored as a string pair in a dictionary. They can be used during model binding, as you'll see in chapter 6.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With