ajax - 如何通过忽略路由来调用控制器方法
问题描述
我在控制器中有这两种方法,我想从 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!");
}});
谢谢。
解决方案
@StephenMuecke 的建议非常好。它的常见问题和路由属性可以帮助您解决类似的问题。在你的情况下,我看到几个问题。
- 您想接收
GetCountryID
实际的字符串 - 您应该使用 int 而不是字符串。 - 您可以使用路由属性来解决这个问题。在您的情况下,请添加
[HttpGet("/AutoComplete/{CountryID}")]
我在这里提供了非常快速的演示: 为什么你应该使用这个解决方案而不是你的?
- 其他开发人员最好为您的操作/资源创建清晰的 url。
- 它真的很容易修改和维护端点。
- 如果遇到类似问题,我建议遵循 RESTFul 指南。你可以在这里阅读更多:https ://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9
推荐阅读
- excel - 查找日期范围内的最小值/最大值
- mysql - 如何批量更新 MySQL 中基于旧值的列值?
- r - 为什么我们应该在 R 中应用 knn() 之前使用 set.seed()?
- javascript - 单击 Javascript 按钮时无法显示 PHP 文件
- python - 从 Nuke 的节点图中提取矢量图像或高分辨率图像
- javascript - 如何使用 Chart JS 启用缩放插件?
- javascript - Javascript在匹配正则表达式中使用变量
- google-cloud-firestore - 在 Google BigQuery 中插入/更新 Firestore 文档导出
- json - 如何确定JQ中是否存在数组
- go - 未捕获的不变违规:存储错误