简体   繁体   中英

Route id not being picked up in Asp.Net Core MVC controller action

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);
}

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?}"); 

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);
}

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....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM