asp.net MVC - C# MVC 路由和 Ajax 调用

本文关键字:MVC Ajax 路由 调用 net asp | 更新日期: 2023-09-27 17:56:07

我有以下控制器:

    public class MyController : BaseController
    {
        public ActionResult Index(string id) { /* Code */ }
        public ActionResult MyAjaxCall(string someParameter) { /* Code */ }
    }

我还在路由配置中添加了以下内容.cs

    routes.MapRoute(
        name: "MyController",
        url: "MyController/{id}",
        defaults: new { controller = "MyController", action = "Index" }
    )

所以我的想法是能够使用这个 url/MyController/{Id} 直接进入索引操作,这似乎有效。

但是,在Index页面上,我需要对 /MyController/MyAjaxCall/{someParameter} 进行 Ajax 调用。但是,此 url 指向索引控制器,并将MyAjaxCall解释为 Index 操作中的 id。

任何想法如何从新添加的路由配置设置中排除此操作?

asp.net MVC - C# MVC 路由和 Ajax 调用

如果您的id只能是整数,则可以向 id 字段添加约束,该约束指定您的 id 只能是数字:

routes.MapRoute(
    name: "MyController",
    url: "MyController/{id}",
    defaults: new { controller = "MyController", action = "Index" },
    constraints: new { id = @"'d+" }  // <- constraints of your parameters
)

在这里,您可以使用适用于您的业务逻辑的任何正则表达式。

此外,请确保在默认路由注册之前注册此路由,在这种情况下,MVC 将首先尝试匹配此路由,并且只有在不匹配时才会尝试匹配默认路由。

听起来您的路线顺序错误。使用 MVC 路由时,第一场比赛始终获胜,因此您必须将最具体的路由放在常规路由之前。

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