Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional id for default action

I got a site with only this Route:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute("Default", "{controller}/{action}/{id}",
        new { controller = "Image", action = "Image", id = UrlParameter.Optional }
        );
}

This is the controller:

public class ImageController : Controller
{
    public ActionResult Image(int? id)
    {
        if (id == null)
        {
            // Do something
            return View(model);
        }
        else
        {
            // Do something else
            return View(model);
        }
    }
}

Now this is the default action so i can access it without an ID just by directly going to my domain. For calling the id it works just fine by going to /Image/Image/ID. However what i want is calling this without Image/Image (so /ID). This doesn't work now.

Is this a limitation of the default Route or is there a way to get this to work?

Thanks

like image 634
Fortitude Avatar asked Feb 05 '26 23:02

Fortitude


1 Answers

Create a new route specific for this url:

routes.MapRoute(
    name: "Image Details",
    url: "Image/{id}",
    defaults: new { controller = "Image", action = "Image" },
    constraints: new { id = @"\d+" });

Make sure you register the above route before this one:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

Otherwise it will not work, since the default route will take precedence.

Here I'm stating that if the url contains "/Image/1" then the ImageController/Image action method is executed.

public ActionResult Image(int id) { //..... // }

The constraint means that the {id} parameter must be a number (based on the regular expression \d+), so there's no need for a nullable int, unless you do want a nullable int, in that case remove the constraint.

like image 110
Jason Evans Avatar answered Feb 09 '26 04:02

Jason Evans