ASP.NET MVC Url.Action routing error

I've been using this for a while, but I can't figure out where the error might be 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 get instead of the expected address http: // localhost: 58296 / Home / Page / 1 one http: // localhost: 58296 / Home / Page? Page = 1

Using

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

      

it works .. please, where is my mistake? I need a link to the image, so if there is a way to insert it into the Html.RouteLink, I'll use that information too.

Thanks in advance.

+2


source to share


2 answers


There are tons of items here for you to fully understand what's going on. Sorry this will be a little longer.

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

      

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

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

      



Second, in your link, you set the page action. The route you are expecting does not take an action as a parameter and the only action it knows about is the index. When Url.Action looks for possible routes in the route table, it will skip the desired route because that route is not accepting page action. The default route is valid, although due to the fact that you are implicitly supplying the Home controller by explicitly providing an action, the page allows the framework to provide a default value for id, string.Empty, and any other parameters referenced as request parameters, page.

When you changed Url.Action to "Index", the Url.Action method checked the route table and found a route with the index action specified for the home controller, with the page parameter, and happily ever after.

Hope this helps and not too confusing.

+8


source


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 anyone could explain this to me, I would appreciate it.

+2


source







All Articles