Jack Ryan
Jack Ryan

Reputation: 8472

ASP.NET MVC Routing: Can I have an action name with a slash in it?

What I want to do is have a page at /Products/Details/{id}, which routes to the action details on ProductsController and also an edit page at /Products/Details/Edit/{id}.

I tried to do this using [ActionName("Details/Edit")] on the action but that doesn't work.

Upvotes: 2

Views: 2629

Answers (3)

Tony Borf
Tony Borf

Reputation: 4660

What you can do is this. Setup a new route like this before the default route;

 routes.MapRoute(
     "PRoute", 
     "{controller}/{action}/{action2}/{id}", 
     null   
 );

then in your Products controller have your action like this, notice that the parameter names match the names in the route.

public ActionResult Details(string action2, string id)
{
    switch (action2)
    {
        case "edit":
            // Do Something.
            return View("edit");
        case "view":
            // Do Something.
            return View("view");
       default :
            // Do Something.
            return View("bad-action-error");
    }
}

Now the Details action will be passed action2 and the id from the url. So a URL like /products/details/view/7 the details action will get "view" and "7" , then you can use a switch or if statement on action2 to continue your processing. This can now easily be expanded to include other sub-actions.

Upvotes: 1

Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24108

Add route like this BEFORE the default one:

routes.MapRoute(
    "DefaultWithDetails",
    "{controller}/Details/{action}/{id}"},
    null);

Upvotes: 1

Lewis
Lewis

Reputation: 5879

You can't have a slash in your action name.

Why not have the following actions?

  • /Products/Details/{id} -For display
  • /Products/Edit/{id} -For edit

My preference would be to do the following:

  • /Products/{id}/View -For display
  • /Products/{id}/Edit/ -For edit

Hope that makes sense!

Upvotes: 5

Related Questions