在Asp.Net Core MVC控制器操作中未获取路由ID

时间:2018-03-13 12:42:21

标签: c# asp.net-core asp.net-core-mvc

给出以下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>

生成此网址:

  

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

但是在此控制器操作中,所选变量始终为0。 为什么控制器操作不从URL路由中获取id? 这是HttpGet控制器操作:

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

3 个答案:

答案 0 :(得分:1)

使用当前的操作定义,MVC会尝试从查询参数填充selected值(默认情况下这是),并在将其作为URL的一部分传递时失败。

因此,如果您希望将其作为URL的一部分,则需要明确指定此作为路由的一部分:

  • 通过路线属性:

    [Route("Product/Products/{selected}")]
    public IActionResult Products(int selected)
    
  • 或者如果您使用约定路由

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

答案 1 :(得分:0)

更改代码并放置id而不是selected

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

答案 2 :(得分:0)

为什么使用“ int selected”?它需要自定义路由。

使用“字符串ID”,默认情况下,MVC会为您处理。 如果您需要输入参数为int,则将其转换为int(在try catch中?)。

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