Optional identifier for the default action

I have 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);
        }
    }
}

      

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

Is this a default route restriction or is there a way to make this work?

thank

+3


source to share


1 answer


Create a new route specific to this URL:

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

      

Make sure you have registered the above route before this:

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

      



Otherwise it won't work as the default route will take precedence.

Here I am arguing that if the url contains "/ Image / 1" then the action method is executed ImageController/Image

.

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

The constraint means the parameter {id} must be a number (based on regex \d+

), so there is no need for a nullable int, unless you want to be a nullable int, in that case remove the constraint.

+3


source







All Articles