I am trying to use the asp-route- to build a query string that I am using to query the database. I am confused on how the asp-route- works because I do not know how to specifically use the route that I created in my cshtml page. For example:
If I use the old school href parameter approach, I can then, inside my controller, use the specified Query to get the parameter and query my database, like this:
If I use this href:
<a href="/Report/Client/?ID=@ulsin.ID">@ulsin.custName</a>
then, in the controller, I can use this:
HttpContext.Request.Query["ID"]
The above approach works and I am able to work with the parameter. However, if I use the htmlHelper approach, such as:
<a asp-controller="Report" asp-action="Client" asp-route-id="@ulsin.ID">@ulsin.custName</a>
How do I get that ID from the Controller? The href approach does not seem to work in this case.
According to the Anchor Tag Helper documentation, if the requested route parameter (id
in your case) is not found in the route, it is added as a query parameter. Therefore, the following final link will be generated: /Report/Client?id=something
. Notice that the query parameter is lowercase.
When you now try to access it in the controller as HttpContext.Request.Query["ID"]
, since HttpContext.Request.Query
is a collection, indexing it would be case-sensitive, and so "ID" will not get you the query parameter "id". Instead of trying to resolve this manually, you can use a feature of the framework known as model binding, which will allow you to automatically and case-insensitively get the value of a query parameter.
Here is an example controller action that uses model binding to get the value of the query parameter id
:
// When you add the id parameter, the framework's model binding feature will automatically populate it with the value of the query parameter 'id'.
// You can then use this parameter inside the method.
public IActionResult Client(int id)