TagHelper for passing route values as part of a link

asp.net Coreasp.net Core-MvcTag Helpers

asp.net Core Problem Overview


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()?

asp.net Core Solutions


Solution 1 - asp.net Core

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>

Solution 2 - asp.net Core

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>

Solution 3 - asp.net Core

you can pass custom ID using below code:

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

Solution 4 - asp.net Core

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmattdwenView Question on Stackoverflow
Solution 1 - asp.net CoreKiranView Answer on Stackoverflow
Solution 2 - asp.net CoreAlex WhiteView Answer on Stackoverflow
Solution 3 - asp.net CoreZubayer Bin AyubView Answer on Stackoverflow
Solution 4 - asp.net CoreAbdul HadeeView Answer on Stackoverflow