capcapdk
capcapdk

Reputation: 179

ASP.NET MVC Route: Product category and slug

I have a ProductController for viewing products. Products have a slug and a category.

I want the following pretty urls (examples)

URL                                               CONTROLLER ACTION                   PARAMETER
www.example.com/products                   -> ProductController.Products      :  "" (empty string)
www.example.com/products/phones            -> ProductController.Products      :  "phones"
www.example.com/products/phones/iPhone     -> ProductController.Details       :  "phones" &"iPhone"

Preferably implemented as route-attributes [HttpGet("route-here")]. But routes.MapRoute in Startup.cs is also ok.

Thanks.

What i've tried The first 2 routes are currently working for me:

[HttpGet("products/{category?}")]
public ActionResult Products(string category)

But the last route does not seem to work:

[HttpGet("products/{category}/{slug}")]
public ActionResult Details(string category, string slug)

Upvotes: 0

Views: 807

Answers (1)

Alex
Alex

Reputation: 38539

I can't believe I've answered this without making you try to solve it yourself, but here's the code

public class ProductController : Controller
{
    [Route("products/{productType}")]
    public ActionResult Products(string productType)
    {

    }

    [Route("products/{productType}/{product}")]
    public ActionResult Details(string productType, string product)
    {

    }
}

Upvotes: 1

Related Questions