0
votes

Given the following HTML:

 <li>
     <a asp-area="" asp-controller="Product" asp-action="Products" asp-route-id="0">
        <i class="si si-drop"></i>
        <span class="sidebar-mini-hide">EnerBurn</span>
      </a>
  </li>

produces this URL:

https://localhost:44356/Product/Products/0

But in this controller action, the selected variable is always 0. Why isn't the controller action picking up the id from the URL route? This is the HttpGet controller action:

public IActionResult Products(int selected)
{
    var pivm = new ProductInfoViewModel {SelectedId = selected};
    pivm= UpdateModelFromSelectedId(pivm);
    return View(pivm);
}
3
have you tried naming your action parameter idEhsan Sajjad
or use asp-route-selected="0" instead of asp-route-idTomas

3 Answers

1
votes

With your current action definition, MVC tries to populate the selected value from query params (this is by default) and fails as you pass it as part of URL.

And so as you want this to be part of URL, you need to specify this explicitly as part of routing:

  • Via route attribute:

    [Route("Product/Products/{selected}")]
    public IActionResult Products(int selected)
    
  • Or if you use the convention routing

    routes.MapRoute("products", {controller=Product}/{action=Products}/{selected?}");
    
1
votes

Change the code and put id instead of selected:

public IActionResult Products(int id)
{
    var pivm = new ProductInfoViewModel {SelectedId = id};
    pivm= UpdateModelFromSelectedId(pivm);
    return View(pivm);
}
0
votes

Why use "int selected"? It requires custom routing.

Use "string id" and MVC will handle it for you by default. If you need the input parameter to be an int, then convert it to an int (in try catch?).

//in: id represents selected index
public IActionResult Products(string id)
{
int selected = Convert.ToUInt32(id);
//do work....
}