0

I want to know if this is possible (it seems like it should be)

I would like to have a route such as:

/events/{id}/addcomment

where the {id} is a param to be used to identify the event to add a comment too. I'm aware that I could simple do /events/addcomment/{id} but this is not how I desire to route this action so this is what I've gotten so far by looking at other SO posts

I register a route in my global.asax file -

        routes.MapRoute(
            "AddComment",
            "Events/{id}/AddComment",
            new { controller = "Events", action = "AddComment", id = "" }
        );

Then my action inside of my events controller -

[ActionName("{id}/AddComment")]
public ActionResult AddComment(int id)
{
    Event _event = db.Events.Find(id);
    var auth = OAContext.LoginRedirect("Must be logged in to add a comment");
    if (auth != null)
        return auth;
    else if (_event == null)
        return HttpNotFound();
    else
        return View(_event);
}

I've tried this with and without the ActionName annotation, not entirely sure what I'm doing wrong here.

Later I plan to have routes such as /events/{eventId}/comment/{commentId}/{action} that will allow users to edit/delete their comments from an event, but first I need to figure out exactly how to route this.

The reason I'm asking this is I have not seen any other samples of parameters proceeding actions in the url, so perhaps I'm just not able to do this and if so than that'd be good to know.

My question: is this url format possible and if so what is the proper way to code this into the routes and controller?

Lazy Coder
  • 1,157
  • 1
  • 8
  • 18
  • 2
    Try it without this: `[ActionName("{id}/AddComment")]` – Martin Feb 15 '13 at 20:44
  • Yeah that actually worked, strange I'm not sure what I changed but I thought that I had originally tested it like that and added the annotation at the end after it failed. – Lazy Coder Feb 15 '13 at 21:09

1 Answers1

1

This is a route that should work:

routes.MapRoute(
   "AddComment",
   "Events/{id}/AddComment",
   new { controller = "Events", action = "AddComment" }
);

You don't need to be using any ActionName attribute on your action for this to work. Just make sure that you have defined this route before your the default route. Also notice that since the {id} route parameter is not the last part of your route definition it cannot be optional anymore. You should always specify a value for it when generating an route.

For example:

@Html.ActionLink(
    "click me", 
    "AddComment", 
    "Events",
    new { id = "123" },
    null
)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That was the tweak I needed to make, putting the route before my default rule, thank you. (as well as removing the annotation) as Martin mentioned above. I must have done this after I added the annotation and did not think to try it without the annotation. – Lazy Coder Feb 15 '13 at 21:16