views:

21

answers:

2

I have a route that looks like this (but I've tried a few different ones):

routes.MapRoute(
  "Metrics",
  "Metrics/{action}/{id}/{resource}/{period}",
  new { controller = "Metrics" }
);

On the MetricsController I have the following actions:

// Index sets up our UI
public ActionResult Index(int id, string resource, string period)

// GetMetrics returns json consumed by ajax graphing tool
public JsonResult GetMetrics(int id, string resource, string period)

How do I generate links and not have Index in the url so that I can do this?:

/Metrics/1234/cpu-0/10m  -> 
           MetricsController.Index(id, string resource, string period)

/Metrics/GetMetrics/1234/cpu-0/10m -> 
           MetricsController.GetMetrics(int id, string resource, string period)

I've tried all sorts of incantations of Html.ActionLink and Html.RouteLink but with no joy.

+1  A: 

You might need two routes for this because optional parameters could be only at the end of the route definition:

routes.MapRoute(
    "ActionlessMetrics",
    "Metrics/{id}/{resource}/{period}",
    new { controller = "Metrics", action = "Index" }
);

routes.MapRoute(
    "Metrics",
    "Metrics/{action}/{id}/{resource}/{period}",
    new { controller = "Metrics" }
);

And to generate those links:

<%= Html.ActionLink("Link1", "Index", "Metrics", 
    new { id = 123, resource = "cpu-0", period = "10" }, null) %>
<%= Html.ActionLink("Link2", "GetMetrics", "Metrics", 
    new { id = 123, resource = "cpu-0", period = "10" }, null) %>

Which will result in:

<a href="/Metrics/123/cpu-0/10">Link1</a>
<a href="/Metrics/GetMetrics/123/cpu-0/10">Link2</a>

and proper action selected.

Darin Dimitrov
Thanks Darin, I thought this might be the way but wondered if it could be done with just one route. This means that conceivably you could end up with route explosion on a fairly large application?
Kev
@Kev, yes that's possible especially if you are some SEO maniac. Personally I wouldn't mind having `Index` in the url to avoid duplicating the route but that's subjective. In large applications you will probably have areas which would allow you to group urls by functionality.
Darin Dimitrov
A: 

hmmm this method doesn't actually seem to do it for me in mvc2. No matter what the action method name still appears in the url, regardless of having a route as above. Html.ActionLink still puts in index such as: <%: Html.ActionLink("Link1", "Index", "Metrics", new { id = 10 }, new { @class = "font11" })%>

still produces Index in the link.

Adam Tuliper