Passage Passage - 1 month ago 11
ASP.NET (C#) Question

ASP.NET Razor: Send variable as parameter

My view contains the following table definition:

<table>
<thead>
<th>Title</th>
<th>Artist</th>
<th>Genre</th>
<th>Price</th>
</thead>
@foreach (var album in Model)
{
<tr>
<td>@album.Title</td>
<td>
@{
foreach (var artist in ViewBag.Artists)
{
if (artist.ArtistID == album.ArtistID)
{ @artist.Name }
}
}
</td>

<td>
@{
foreach (var genre in ViewBag.Genres)
{
if (genre.GenreID == album.GenreID)
{ @genre.Name }

}
}
</td>

<td>@album.Price</td>
<td>
<a asp-action="Details" asp-controller="Albums">Details </a>
<a asp-action="Edit" asp-controller="Albums">Edit </a>
<a asp-action="Delete" asp-controller="Albums">Delete</a>
</td>
</tr>

}
</table>


The
Details
,
Edit
, and
Delete
options in the final column need to be keyed to the
AlbumID
property of the
album
variable, in order to ensure that the redirect operates on the proper album. I had thought the parameter for this might be
asp-parameter
, much like the action is set by
asp-action
, but this does not appear to exist.

What is the proper method to pass a variable as a URL parameter (for instance,
/Albums/Details/var
), and what name is used to retrieve this on the other side?

Shyju's answer deals with passing the parameter; my attempts at retrieving the parameter thus far have been as follows:

<%=Url.RequestContext.RouteData.Values["id"]%>
- Fails to load, invalid character
<
.

ViewContext.RouteData.Values["id"]
- Fails to load, cannot compare
int
and
object
using
==
.

RouteData.Values["id"]
- Compilation error, name does not exist in current context.

Answer

When using link tag helper, You can pass additional information to the action method using the asp-route-[paramName] attribute. For example, if you want to pass the album id to the id parameter of your details action method, you can do this

<a asp-action="Details" asp-controller="Albums" asp-route-id="@album.ID">Details </a>

This will generate the markup like below

<a href='/Albums/Details/101'>Details</a>

Where 101 will be replaced by an actual Album Id value.

Assuming your Details action method has a parameter named id

public ActionResult Details(int id)
{
  // to do : Get the album using the id and send something to the view
}