【问题标题】:How to call controller method by ignoring routes如何通过忽略路由来调用控制器方法
【发布时间】:2018-06-15 09:39:11
【问题描述】:

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

谢谢。

【问题讨论】:

  • 为什么不将[Route("/AutoComplete/GetCountryID/{CountryID}")]添加到第二种方法
  • 试过但没用。

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


【解决方案1】:

我通过将行改为

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

【讨论】:

    【解决方案2】:

    @StephenMuecke 的建议非常好。它的常见问题和路由属性可以帮助您解决类似的问题。在你的情况下,我发现很少有问题。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      相关资源
      最近更新 更多