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?

有帮助吗?

解决方案

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
)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top