【问题标题】:Unable to call Web API controller method with ajax in Asp .Net无法在 Asp .Net 中使用 ajax 调用 Web API 控制器方法
【发布时间】:2017-01-26 19:24:23
【问题描述】:

无法在 Asp.Net 中使用 ajax jquery 调用 Web API 控制器方法。

$(document).ready(function () {
    $.ajax({
        url: '/UnitsAPI/GetZones',
        method: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: { "knownCategoryValues": 1, "category": Zone },
        success: function (response) {
            // $('#lblData').html(JSON.stringify(response));
        },
        error: function (error) {
            console.log(error);
        }
    });
});

我的控制器

[HttpGet] 
public IHttpActionResult GetZones(string knownCategoryValues, string category) 
{ 
    SqlConnection sqlConn = new SqlConnection(); 
    DataSet ds = new DataSet(); 
    string strConn = GetConnectionInfo(); 
    sqlConn = new SqlConnection(strConn); 
    sqlConn.Open(); int stateID = 1; 
    NonCellUnit unit = new NonCellUnit();
    List<Unit> unitList = new List<Unit>(); 
    unitList = unit.GetChildUnits(stateID, true); return Ok(unitList); 
}

【问题讨论】:

  • 添加你的 WebApi 方法
  • 当您在浏览器中打开该网址时会发生什么?为了提供帮助,我们需要更多关于实际情况的信息。
  • @Div 由于使用了控制器这个词,我假设它是 MVC,所以 URL 将是控制器和操作。
  • 当我在 URL 中打开它时,它是 Web APi 中的触发方法,但如果我在应用程序端运行它不会触发。但是这个 Ajax 我是从 .ASPX 表单调用的。
  • @Archer,是的,你是对的,这里我们还要看看OP是如何在控制器端定义参数的。

标签: c# jquery asp.net asp.net-web-api


【解决方案1】:

添加属性路由开始你的控制器

[Route("api/UnitsAPI/GetZones")]

请求为

$(document).ready(function () {
    $.ajax({
        url: '/api/UnitsAPI/GetZones',
        method: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: { "knownCategoryValues": 1, "category": Zone },
        success: function (response) {
            // $('#lblData').html(JSON.stringify(response));
        },
        error: function (error) {
            console.log(error);
        }
    });
});

【讨论】:

    【解决方案2】:

    这里你使用的是 WebApi,所以你的路由中有默认的 api

    所以,您可以在 ajax 调用中尝试像 url: 'api/UnitsAPI/GetZones' 这样更改数据,例如

    data: { "knownCategoryValues": "1", "category": Zone }
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      相关资源
      最近更新 更多