【问题标题】:Passing parameter over jQuery GET call receive null on server side通过 jQuery GET 调用传递参数在服务器端接收 null
【发布时间】:2023-03-16 11:04:02
【问题描述】:

我正在尝试在 jQuery 中调用 GET 并传递一个参数,这就是我正在做的事情

function getChirurghi() {
    var id = "1";
    $.ajax({
        type: "GET",
        url: "/api/ControllerName/GetDataHere",
        contentType: "application/json; charset=utf-8",
        data: id,
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        failure: function (data) {
            alert(data.responseText);
        },
        error: function (data) {
            alert(data.responseText);
        }
    });
}

在服务器端调用了控制器,但我得到的数据始终为空...

[HttpGet]
public IEnumerable<TypeOfObject> GetDataHere([FromBody]string id)
{}

知道这是怎么回事吗?

【问题讨论】:

    标签: javascript c# jquery asp.net .net


    【解决方案1】:

    您需要为该值指定一个键,以便 ModelBinder 可以识别并使用它:

    data: { id: id },
    

    您还需要删除操作签名中的[FromBody] 属性,因为GET 数据是在URL 中发送的(作为查询字符串的一部分,或者在路由结构中)。

    最后,$.ajax() 的选项对象没有failure 属性,因此可以将其删除,因为它是多余的。

    【讨论】:

    • 完美!谢谢。另一个简短的问题。有什么办法可以在同一个控制器中放置更多不同名称的 get 方法?
    • 没问题,改方法名就好了。没问题,很乐意提供帮助。
    • 嘿@Rory McCrossan 很抱歉再次打扰。我尝试在同一个控制器中添加不同的get method,但出现以下错误:Multiple actions were found that match the request: GetDataHere on type WebApplication.Controllers.ControllerName GetMoreDataHere on type WebApplication.Controllers.ControllerName ExceptionType:System.InvalidOperationException
    • 好的。我回答我自己。我必须将{action} 添加到路由模板routeTemplate: "api/{controller}/{action}/{id}"
    【解决方案2】:

    我赞成@RoryMcrossan,但还有另一种解决方案。

    您可以将其添加到 url 的末尾。

    function getChirurghi() {
    var id = "1";
    $.ajax({
        type: "GET",
        url: "/api/ControllerName/GetDataHere/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        failure: function (data) {
            alert(data.responseText);
        },
        error: function (data) {
            alert(data.responseText);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多