【问题标题】:MVC custom (attribute) routing with an optional parameter does not work带有可选参数的 MVC 自定义(属性)路由不起作用
【发布时间】:2015-05-27 13:06:15
【问题描述】:

我的控制器如下所示:

[HttpGet]
[Route("{brand}/{category}/{subcategory?}/{productid:int:min(9000)}", Name="ProductDetails")]
public ActionResult Details(int productid)
{ //...}

我还尝试在子类别末尾不带问号,因为它可以为空。

[Route("{brand}/{category}/{subcategory}/{productid:int:min(9000)}", Name="ProductDetails")]

我的观点是这样的:

 <a href="@Url.RouteUrl("ProductDetails", 
      new { brand = item.Brand, 
            category = item.CatCodeNaam, 
            subcategory = item.SubCategoryName, 
            productid = item.ID })">test</a>
 <a href="@Url.Action("Details", "Products", 
      new { brand = item.Brand, 
            category = item.CatCodeNaam, 
            subcategory = item.SubCategoryName, 
            productid = item.ID })">test</a>

SubCategoryName 不为空时,这两种方法都非常有效。但是当它为空时该怎么办?我无法添加其他路由,因为它将具有相同数量(和类型)的输入参数,只有一个 int。

当我有这个控制器时:

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{productid:int:min(9000)}", Name = "ProductDetails")]
[Route("{brand}/{category}/{productid:int:min(9000)}", Name = "ProductDetails2")]
public ActionResult Details(int productid)

当子类别为空时,第一个&lt;a 工作,当子类别不为空时,带有路由名称的第二个&lt;a 工作。有没有一种方法只有一个版本的 &lt;a 并且可能只有一个路由作为 Details 方法的属性?

【问题讨论】:

    标签: asp.net-mvc attributerouting


    【解决方案1】:

    用我剃须刀中的这条紧凑线“修复”了它:

    <a href="@(!string.IsNullOrWhiteSpace(item.SubCategoryName) ? Url.RouteUrl("ProductDetails", new { brand = item.Brand, category = item.CatCodeNaam, subcategory = item.SubCategoryName, productid = item.ID }) : Url.Action("Details", "Products", new { brand = item.Brand, category = item.CatCodeNaam, subcategory = item.SubCategoryName, productid = item.ID }))">
    

    感谢https://stackoverflow.com/a/4092187/169714

    但仍然期待更好的解决方案,所以我不会接受自己的答案并希望有更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2016-01-26
      • 2015-09-18
      • 2011-04-08
      • 1970-01-01
      • 2017-05-08
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多