【问题标题】:C# MVC Routing and Ajax CallsC# MVC 路由和 Ajax 调用
【发布时间】:2016-11-12 08:42:54
【问题描述】:

我有以下控制器:

    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/{Id} 直接进入索引操作,这似乎可行。

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

有什么想法可以从遵循新添加的路由配置设置中排除此操作吗?

【问题讨论】:

  • 使用url: "MyController/MyAjaxCall/{someParameter}"defaults: new { controller = "MyController", action = "MyAjaxCall" } 包含一个额外的路由

标签: c# asp.net-mvc routes url-routing asp.net-mvc-routing


【解决方案1】:

如果你的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会首先尝试匹配这个路由,只有当它不匹配时才会尝试匹配默认路由。

【讨论】:

  • 那么在不满足约束的情况下,会不会使用默认路由来路由URL呢?
  • @JEPAAB 是的,如果约束不匹配,则认为路由不匹配
  • 但是在我的情况下,我需要将参数作为字符串。是否可以添加约束以排除“MyAjaxCall”参数?
  • @JEPAAB 您可以使用任何正则表达式。因此,如果您定义匹配除“MyAjaxCall”之外的任何文本的正则表达式,那么这将起作用。这是如何编写正则表达式stackoverflow.com/a/14147470的示例,虽然我还没有测试过
【解决方案2】:

听起来您的路线顺序错误。使用 MVC 路由时,第一个匹配总是获胜,所以你 must place the most specific routes first before general routes

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 }
);

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2016-05-26
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多