MVC Route with Optional Section
I would like to create a route for my MVC page that looks like this:
/Articles/
/Articles/Page/2 /Articles/Page/3I want the default page to be 1, but if the page is 1, then don't actually show the /Page/ piece.
I started out with:
routes.MapRoute(
"Articles",
"Articles/Page/{page}开发者_Go百科",
new { controller = "Articles", action = "Index", page = 1 }
);
The problem with this is that when I do:
<%= Html.RouteLink("Articles", new { page = 1 }) %>
My route ends up being: /Articles/Page/
You might need two route definitions for this (untested):
routes.MapRoute(
"ArticlesDefault",
"Articles",
new { controller = "Articles", action = "Index", page = 1 }
);
routes.MapRoute(
"Articles",
"Articles/Page/{page}",
new { controller = "Articles", action = "Index" }
);
and your controller action:
public ActionResult Index(int page)
{
...
}
Put both in:
// This will match routes where the page equals one. Since the page can't
// be specifed here, it will drop to the next one for page values other
// than 1.
routes.MapRoute("Articles",
"Articles",
new { controller = "Articles", action = "Index", page = 1 }
);
// This route handles pages other than 1
routes.MapRoute(null,
"Articles/Page/{page}",
new { controller = "Articles", action = "Index" }
);
You don't need to do anything with the controller.
精彩评论