1

I having some problems overloading the Index action in a controller. In the controller I have the following actions:

public ActionResult Index(int id)
{
    return View();
}

public ActionResult Index()
{
    return View();
}

Going to either URL (controllername/ or controllername/1) results in a 500 error. However when I use:

public ActionResult Index(int? id)
{
    return View();
}

The controllername/ URL works but controllername/1 results in a 404 error. My global.asax is pretty vanilla:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

What I would like to do is be able to handle a null id as well as an integer id value. Any suggestions would be greatly appreciated.

Thanks!

1
  • 2
    did you try (with the int?) to make controllername/Index/1 ? Commented May 13, 2012 at 15:10

2 Answers 2

1

I think you will need to explicit the routes for that:

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

if it doesn't work, you may need to be more explicit and add this before:

routes.MapRoute(
    "ControllerName",
    "ControllerName",
    new { controller = "ControllerName", action = "Index"}
);
Sign up to request clarification or add additional context in comments.

Comments

1

I think you don't need an overload here, but just need a check inside the index action for the null. Overloading action is not a good idea, because framework would have no idea of which action to call incase of null index.

Adding custom routing for every action overload will cause slower response time because of too many custom routes to resolved.

Comments

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.