Question

I want to make a route where the controller name is not displayed in the URL.

I started with this route:

routes.MapRoute(
    name: "ViewTag",
    url: "tag/tagged/{tag}",
    defaults: new { controller = "Tag", action = "Tagged" }
);

And controller method:

public class TagController : Controller
{
    public ActionResult Tagged(string tag)
    {

Which works but generates URL: tag/tagged/money

I wanted to use the URL: tagged/money

I changed the route to remove the controller name:

routes.MapRoute(
    name: "ViewTag",
    url: "tagged/{tag}",
    defaults: new { controller = "Tag", action = "Tagged" }
);

Which does route correctly when I manually type in the URL: tagged/money but, it doesn't generate the correct routes.

@Html.ActionLink(tag.Text, "tagged", new { @tag = tag.Text })

or

@Html.ActionLink(tag.Text, "tagged", "tag", new { @tag = tag.Text }, null)

Both generate the original and wrong URL: tag/tagged/{tag}

I thought the route config was used to both parse incoming URL's and generate URL's?

Était-ce utile?

La solution

You can use Html.RouteLink method after dropping tagged from the route URL:

@Html.RouteLink(tag.Text, "ViewTag", new { @tag = tag.Text })
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top