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!

Andy Evans
  • 6,997
  • 18
  • 72
  • 118

2 Answers2

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"}
);
Ivo
  • 8,172
  • 5
  • 27
  • 42
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.

Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42