views:

3126

answers:

2

Hi, I've been using this some while now, but I can't seem to figure out, where could be mistake in this simple code:

<a href="<%= Url.Action("Page", new { page=(Model.PageIndex + 1) }) %>" >a</a>

With this routing table:

routes.MapRoute(
            "Paging",
            "Home/Page/{page}",
            new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

And of course this method

public ActionResult Index(int? page)

I am getting instead of expected address http://localhost:58296/Home/Page/1 the one http://localhost:58296/Home/Page?page=1

When using

<%= Html.RouteLink("a", "Paging", new { page=(Model.PageIndex+1) }) %>

it works.. Please, where is my mistake? I want image link, so if there is a way to insert it into Html.RouteLink, I would appriciate that info too.

Thanks in advance.

A: 

I don't know why, but

<%= Url.Action("Index", new { page=(Model.PageIndex + 1) }) %>

works and it displays and directs to /Home/Page/1 . If someone could explain it to me, I would be gratful.

Trimack
+3  A: 

There's a bunch of items to cover here for you to fully understand what's happening. Sorry, this will be a bit long.

routes.MapRoute(
    "Paging",
    "Home/Page/{page}",
    new { controller = "Home", action = "Index" }
);

First, this is the route you want to hit. You do not include the action route parameter, '{action}', in the route path. The only action this route can possibly take is the value you have specified as the default action value "Index".

<a href="<%= Url.Action("Page", new { page=(Model.PageIndex + 1) }) %>" >a</a>

Second, in your link you are setting an action of Page. The route you are expecting does not accept action as a parameter and the only action it is aware of is Index. When Url.Action looks for possible routes in your route table, it will skip the route you want because that route does not accept an action of Page. The default route is valid though because you are implicitly supplying a controller, Home, explicitly supplying an action, Page, allowing the framework to supply a default for id, string.Empty, and any other parameters are tacked on as query parameters, page.

When you changed the Url.Action to "Index", the Url.Action method inspected the routes table and found the route with the action of Index specified for the Home controller with a parameter of page and everything is happier.

Hope that helps and isn't too confusing.

Chuck