Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TagHelper for passing route values as part of a link

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

like image 461
mattdwen Avatar asked May 04 '15 00:05

mattdwen


People also ask

What is asp all route data?

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.

Which of these helpers is used to specify name of controller form will redirect to?

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.

What is the route for value?

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.


2 Answers

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>

like image 108
Kiran Avatar answered Sep 28 '22 05:09

Kiran


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> 
like image 37
Alex White Avatar answered Sep 28 '22 05:09

Alex White