Reputation:
in the index.cshtml I use an anchor tag helper as
<a asp-action="Edit" asp-route-id="@Model.Id" asp-route-firstname="@Model.Name"</a>
and in the action method
public IActionResult Edit(string id, string firstname)
{
// id and firstname are assigned correct values
// but RouteData.Values only has three entries which are: controller, action and id, where is firstname?
}
But I cannot access the firstname value via RouteData.Values["firstname"];
and I can access the id value via RouteData.Values["id"];
, how come it works for id but not for any other custom attributes?
Upvotes: 0
Views: 42
Reputation: 388443
RouteData
will only contain data that is relevant to routing. What data this is depends on the route template that is used to navigate to your action.
The default route template looks like this: {controller=Home}/{action=Index}/{id?}
. Ignoring the default values, the template is just this: {controller}/{action}/{id?}
.
So there are three slots in the route template: controller
, action
, and an optional id
. These are the values that you will be able to see in RouteData.Values
because those values were used to match the route template.
You can also see this when you look at the URL that gets generated by the tag helper. It should look somewhat like this: /Home/Edit/123?firstname=name
. The id
is part of the route, while the firstname
is only passed as a query argument.
That also means that you can access firstname
through HttpContext.Request.Query
which contains the query arguments that were passed. Note that id
is not included there though because it is passed as route data instead of as query data.
Now, when you use model binding with your controller action, you luckily don’t need to make this distinction. The default behavior will allow you to get both route parameters and query parameters by simply specifying them as parameters to the action method. And using model binding is certainly the recommended way to access these values, making RouteData.Values
and Request.Query
rather low-level mechanisms.
Upvotes: 4