Question

I want to use Html.ActionLink to return an anchor tag with href like /Product/22/Product-Name, where Product is my controller name and 22 is my id and Product-Name is my title.

In my global.asax, I have set the following route :

routes.MapRoute(
  "ProductRoute", // Route name
  "Product/{id}/{title}", // URL with parameters
  new { controller = "Product", action = "Index", id = UrlParameter.Optional });

I tried using following code

@Html.ActionLink(model.Name, null, "Product", 
             new { id = model.Id, title = model.Name.Replace(" ","-") }, null)

but it yields Product/Browse/22?title=Product-Name. This code is in Browse View returned by Browse action of Catalog controller and that's why it picks up the Browse in between.

Strangely, the same code works fine in the Index View returned by Index action of the Home Controller. What's the reason for this difference? . Am I missing something or this is a bug in Asp.net MVC3.

What Should I do to achieve my stated URL format. For the meantime, I am using this code

<a href="/Product/@product.Id/@product.Name.Replace(" ","-")">@product.Name</a>
Était-ce utile?

La solution

make sure you have defined the custom route before the default route and try

@Html.ActionLink(model.Name,
                  "Index",
                 new {controller="Product", id = model.Id, title = model.Name.Replace(" ","-") }, null)

the first parameter is the DisplayName, second the ActionResult's name and then the RouteValues

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top