Reputation: 2423
The URL for any product details page on our site is like this:
http://example.com/Product/Index/pid219
Where:
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. Please help me, how I can achieve my goal here. Also specify, if the new routes have to be declared before or after the default one.
Upvotes: 1
Views: 8151
Reputation: 165
I would like this page to be accessible as http://example.com/Product/pid219 OR http://example.com/Product/name-of-the-product/pid219 For you :
routes.MapRoute(
name: "ProductRoute1",
url: "Product/{id}",
defaults: new {controller = "Product", action = "Index", id = "" }
);
http://example.com/Product/name-of-the-product/pid219
routes.MapRoute(
name: "ProductRoute1",
url: "Product/{*action}/{id}",
defaults: new { controller = "Product", action = "Index", id = "" }
);
Upvotes: 3
Reputation: 593
Issue is coming because in the routes whatever route matches first will be used. Sililar to switch
statement. In your case it matched with
routes.MapRoute(
name: "ProductRoute1",
url: "{controller}/{id}",
defaults: new { controller = "Product", action = "Index", id = "" }
);
If the new functionality is needed only in one controller then its better to add the route directly for this. Something like below
routes.MapRoute(
name: "ProductRoute1",
url: "Product/{id}",
defaults: new { controller = "Product", action = "Index", id = "" }
);
Upvotes: 1