首页 > 解决方案 > 如何通过忽略路由来调用控制器方法

问题描述

我在控制器中有这两种方法,我想从 js 调用 GetCountryId 并将 Id 传递给它,但是由于路由它总是命中 Index 方法,如何解决这个问题?

[Route("/AutoComplete/{id}")]
    public IActionResult Index(string id, string text, int limit,int? CountryId)
    {
    //Some Code
    return View();
}
public IActionResult GetCountryID(string CountryID)
    {
        //Some Code 
        return View();
    }

JS代码是

$.ajax({
    type: 'get'
    url: '/AutoComplete/GetCountryID',
    data: { CountryID: 100},
    success: function (result) {
        alert("Success!");
    }});

谢谢。

标签: ajaxroutingasp.net-core-mvc

解决方案


@StephenMuecke 的建议非常好。它的常见问题和路由属性可以帮助您解决类似的问题。在你的情况下,我看到几个问题。

  1. 您想接收GetCountryID实际的字符串 - 您应该使用 int 而不是字符串。
  2. 您可以使用路由属性来解决这个问题。在您的情况下,请添加

[HttpGet("/AutoComplete/{CountryID}")]

我在这里提供了非常快速的演示: 路由属性演示 为什么你应该使用这个解决方案而不是你的?

  1. 其他开发人员最好为您的操作/资源创建清晰的 url。
  2. 它真的很容易修改和维护端点。
  3. 如果遇到类似问题,我建议遵循 RESTFul 指南。你可以在这里阅读更多:https ://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

推荐阅读