How to setup a wildcard route in MVC
03:57 21 Sep 2018

The URL for any product details page on our site is like this:
http://example.com/Product/Index/pid219

Where:

  • Product - is the name of the controller
  • Index - is the name of the method and
  • pid219 - ID of the product

I would like this page to be accessible as
http://example.com/Product/pid219
OR
http://example.com/Product/name-of-the-product/pid219

So, I modified the RouteConfig.cs to this:

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

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

The page is now accessible as desired, however, there is a problem in all other pages which make Ajax call on button clicks. For e.g: The SignIn button click isn't working.

The controller name is SignIn and there are two methods - Index (which loads the page), SignInUser (which is triggered on ajax request)

When I click on the Sign In button, the Index method is hit now instead of the SignInUser method.

function SignInUser() {    
    $.ajax({
        type: "POST",
        url: '@Url.Action("SignInUser", "SignIn")',            
        data: '',
        contentType: "application/json; charset=utf-8",
        dataType: "json",            
        success: function (response) {                               
        }
    });        
} 

If we set a new route, should the URL in ajax call also needs to be changed. How I can achieve my goal here? Also specify, if the new routes have to be declared before or after the default one.

c# asp.net-mvc