如何通过忽略路由来调用控制器方法

时间:2018-06-15 09:39:12

标签: ajax routing asp.net-core-mvc

我在控制器中有这两个方法,我想从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!");
    }});

感谢。

2 个答案:

答案 0 :(得分:0)

我通过将行改为

解决了这个问题
 url: '/AutoComplete/GetCountryID/',

答案 1 :(得分:0)

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

  1. 您希望在GetCountryID操作中接收字符串 - 您应该使用int而不是string。
  2. 您可以使用路由属性来解决此问题。在您的情况下,请添加
  3. [HttpGet("/AutoComplete/{CountryID}")]

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

    1. 其他开发人员可以更好地为您的操作/资源创建清晰的网址。
    2. 它很容易修改和保留端点。
    3. 我建议在出现类似问题时遵循RESTFul指南。您可以在此处阅读更多内容:https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9