【发布时间】:2019-02-25 13:54:39
【问题描述】:
我们网站上任何产品详细信息页面的 URL 如下所示:
http://example.com/Product/Index/pid219
地点:
- Product - 是控制器的名称
- Index - 是方法的名称和
- pid219 - 产品 ID
我希望这个页面可以作为
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,有两种方法——Index(加载页面),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是否也需要改变。 请帮助我,我如何在这里实现我的目标。还要指定是否必须在默认路由之前或之后声明新路由。
【问题讨论】:
-
这可能是因为第一个路由首先匹配,无条件。您应该考虑将
constraints与defaults一起使用,以确保您控制哪些特定请求通过此附加路由。 -
您需要创建第一条路线
url: "Product/{id}",。第二次也将{controller}更改为Product。要生成 slug 路线,请参阅 how to implement url rewriting similar to SO
标签: c# asp.net-mvc