Generate Asp-route attributes conditionally

141 Views Asked by At

I'm using the razor tag helper asp-route-xxx to generate anchor links from a model in the view.

     <a asp-page="/Products"
      asp-route-currentpage="@i"
      asp-route-minprice="@Model.MinPrice"
      asp-route-maxprice="@Model.MaxPrice">Products</a>

The generated url is /products?currentpage=3&minprice=10&maxprice=100. Is it posible no to create the query parts for default values (0)?

For example if min-price is 0, then is no need to generate the &minprice=0 part in query string.

I tried something like this but razor is not happy, you can't write c# inside html attributes.

 @if(FilterModel.MinPrice > 0 )
 {
    asp-route-minprice="@Model.MinPrice"
 }
 @if(FilterModel.MaxPrice > 0 )
 {
    asp-route-maxprice="@Model.MaxPrice"
 }
1

There are 1 best solutions below

0
Dimitris Maragkos On BEST ANSWER

You can do it like this:

<a asp-page="/Products"
   asp-route-currentpage="@i"
   asp-route-minprice="@(Model.MinPrice != default ? Model.MinPrice : null)"
   asp-route-maxprice="@(Model.MaxPrice != default ? Model.MaxPrice : null)">Products</a>

Or:

@{
    int? minPrice = Model.MinPrice != default ? Model.MinPrice : null;
    int? maxPrice = Model.MaxPrice != default ? Model.MaxPrice : null;
}
<a asp-page="/Privacy"
   asp-route-currentpage="@i"
   asp-route-minprice="@minPrice"
   asp-route-maxprice="@maxPrice">Products</a>