我们网站上任何产品详细信息页面的URL如下:
http://example.com/Product/Index/pid219
位置:
我希望此页面可作为
访问
http://example.com/Product/pid219
或
http://example.com/Product/name-of-the-product/pid219
因此,我将RouteConfig.cs
修改为:
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 }
);
}
现在可以根据需要访问该页面,但是,在所有其他页面中存在一个问题,这些问题使Ajax在单击按钮时调用。 例如:“登录”按钮无法正常工作。
控制器名称为SignIn,有两种方法-索引(用于加载页面),SignInUser(在ajax请求上触发)
当我单击“登录”按钮时,现在单击了Index方法而不是SignInUser方法。
function SignInUser() {
$.ajax({
type: "POST",
url: '@Url.Action("SignInUser", "SignIn")',
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
});
}
如果我们设置了新的路由,那么也需要更改ajax调用中的url。 请帮助我,如何在这里实现我的目标。还指定是否必须在默认路由之前或之后声明新路由。
答案 0 :(得分:1)
问题来了,因为在路线中将使用首先匹配的路线。与switch
语句相似。在您的情况下,它与
routes.MapRoute(
name: "ProductRoute1",
url: "{controller}/{id}",
defaults: new { controller = "Product", action = "Index", id = "" }
);
如果仅在一个控制器中需要新功能,则最好为此直接添加路由。像下面这样
routes.MapRoute(
name: "ProductRoute1",
url: "Product/{id}",
defaults: new { controller = "Product", action = "Index", id = "" }
);
答案 1 :(得分:1)
我希望此页面可以通过 http://example.com/Product/pid219 要么 http://example.com/Product/name-of-the-product/pid219 为您:
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 = "" }
);