1

I have an Asp.Net Mvc website that has a listing controller. The route looks like this:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MySite.Web.Controllers" }
);

Pretty standard. Now I have a number of controller actions in my listing controller. I would like to be able to either go to /listing/84 and have it go to the Index action or to /listing/create, /listing/edit, /listing/favorite, or /listing/others and have it go to the the corresponding actions. For most of my routes this is already the case. This is my controller code:

public ActionResult Index(long? id)
{
    // my code that never gets hit
}

Am I missing something?

1
  • I edited the question to inform everyone that I have multiple actions in the controller. Commented Sep 24, 2012 at 7:48

2 Answers 2

3

You could define a specific route for this and a constraint for the id:

routes.MapRoute(
    "ActionLess",
    "{controller}/{id}",
    new { controller = "Home", action = "Index" },
    new { id = @"^[0-9]+$" },
    new string[] { "MySite.Web.Controllers" }
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MySite.Web.Controllers" }
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so so so much. Elegant solution indeed.
0

You can create two new route for it

For lisitng/Create for navigating Create Action

routes.MapRoute(
     "listingCreate", // Route name
     "listing/Create", // URL with parameters
      new { controller = "listing", action = "Create" } 
);

For Index Action when passing Id

routes.MapRoute(
     "lisingid", // Route name
     "listing/{Id}", // URL with parameters
      new { controller = "listing", action = "Index", id = UrlParameter.Optional } 
);

I hope, It will help you.

1 Comment

One way to do it. I don't think it is a bad solution, but if I have 20 different actions then I will have to make 20 different methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.