0

My controller looks like this:

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

I also tried without the questionmark on the end of the subcategory because it can be null.

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

I have this in my razor views:

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

Both methods work great when SubCategoryName is not empty. But what to do when it is empty? I cannot add an other route, because it will have the same amount (and type) of input parameters, just one int.

When I have this controller:

[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)

the first <a work when subcategory is empty and the second <a with the routename works when subcategory is not empty. Is there a method to have just one version of the <a and perhaps just one route as attribute of the Details method?

JP Hellemons
  • 5,977
  • 11
  • 63
  • 128

1 Answers1

0

"Fixed" it with this compact line in my razor:

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

thanks to https://stackoverflow.com/a/4092187/169714

Still looking forward to a better solution though, so I won't accept my own answer and hope that there is a better solution.

Community
  • 1
  • 1
JP Hellemons
  • 5,977
  • 11
  • 63
  • 128