URL routing requires /Home/Page?page=1 instead of /Home/Page/1

- 1 answer

Ad

I am trying to build my ASP.NET MVC 4.5 project to use search engine friendly URLs. I am using the following route mapping.

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}/{title}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
);

The intention is so that I can create URLs like this:

Mysite.com/Home/Page/1/this-title-bit-is-just-for-show

but it fails and I have to use URLs like this:

Mysite.com/Home/Page?page=1

In case it matters, the Controller Action that this link points to is below:

public ActionResult Page(int page)
{
    PostModel pm = new PostModel(page);
    return View(pm);
}

And I am generating URLs like this:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="@Url.Action("Page", "Home", new { page = 1 })">1</a>

Can someone tell me where I am going wrong?

Ad

Answer

Ad

Instead of

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="@Url.Action("Page", "Home", new { page = 1 })">1</a>

Use

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="@Url.Action("Page", "Home", new { id = 1 })">1</a> //instead of page use id here

and change action method as shown :-

public ActionResult Page(int id) //instead of page use id here
{
    PostModel pm = new PostModel(id);
    return View(pm);
}
Ad
source: stackoverflow.com
Ad