C#MVC路由和Ajax调用

C#MVC路由和Ajax调用,c#,asp.net-mvc,routes,url-routing,asp.net-mvc-routing,C#,Asp.net Mvc,Routes,Url Routing,Asp.net Mvc Routing,我有以下控制器: public class MyController : BaseController { public ActionResult Index(string id) { /* Code */ } public ActionResult MyAjaxCall(string someParameter) { /* Code */ } } 我还在RouteConfig.cs中添加了以下内容 routes.MapRout

我有以下控制器:

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

        public ActionResult MyAjaxCall(string someParameter) { /* Code */ }
    }
我还在RouteConfig.cs中添加了以下内容

    routes.MapRoute(
        name: "MyController",
        url: "MyController/{id}",
        defaults: new { controller = "MyController", action = "Index" }
    )
因此,我的想法是能够使用这个url直接转到索引操作,这似乎是可行的

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


您知道如何从新添加的路由配置设置中排除此操作吗?

如果您的
id
只能是整数,您可以在id字段中添加一个约束,该约束指定您的id只能是数字:

routes.MapRoute(
    name: "MyController",
    url: "MyController/{id}",
    defaults: new { controller = "MyController", action = "Index" },
    constraints: new { id = @"\d+" }  // <- constraints of your parameters
)
routes.MapRoute(
名称:“MyController”,
url:“MyController/{id}”,
默认值:新建{controller=“MyController”,action=“Index”},

约束:新建{id=@“\d+”}/如果您的
id
只能是整数,则可以向id字段添加约束,该约束指定您的id只能是数字:

routes.MapRoute(
    name: "MyController",
    url: "MyController/{id}",
    defaults: new { controller = "MyController", action = "Index" },
    constraints: new { id = @"\d+" }  // <- constraints of your parameters
)
routes.MapRoute(
名称:“MyController”,
url:“MyController/{id}”,
默认值:新建{controller=“MyController”,action=“Index”},

约束条件:新建{id=@“\d+”}/听起来您的路由顺序不正确。当使用MVC路由时,第一个匹配总是获胜,所以您可以


听起来你的路线顺序不对。当使用MVC路线时,第一场比赛总是赢的,所以你


使用
url:“MyController/MyAjaxCall/{someParameter}”和
默认值:新建{controller=“MyController”,action=“MyAjaxCall”}
使用
url:“MyController/MyAjaxCall/{someParameter}”和
默认值:新建{controller=“MyController”,action=“MyAjaxCall”}包含一个附加路由
因此,当不满足约束时,URL是否会使用默认路由进行路由?@JEPAAB是的,如果约束不匹配,则认为路由不匹配。但是在我的情况下,我需要将参数设置为字符串。是否可以添加约束以排除“MyAjaxCall”参数?@JEPAAB您可以使用任何正则表达式。因此,如果您定义的正则表达式匹配除“MyAjaxCall”之外的任何文本,那么这将起作用。下面是如何编写正则表达式的示例,尽管我没有测试过这一点。因此,当不满足约束时,URL是否会使用默认路由进行路由?@JEPAAB是的,如果约束不匹配,则认为路由不是m然而,在我的例子中,我需要将参数设置为字符串。是否可以添加一个约束以排除“MyAjaxCall”参数?@JEPAAB您可以使用任何正则表达式。因此,如果您定义的正则表达式与除“MyAjaxCall”之外的任何文本匹配,则这将起作用。下面是编写正则表达式的示例,尽管我有我没有测试过这个