简体   繁体   English

如何将 2 个变量从 jquery AJAX 传递给 ASP.Net WebApi2 方法?

[英]How to pass 2 variables from jquery AJAX to ASP.Net WebApi2 method?

I can write a JQuery AJAX call to a webapi2 (asp.net) controller with only 1 parameter just fine (one json object), but when attempting to send 2 parameters (a string and an integer) to a call with all else remaining the same, I get我可以写一个 JQuery AJAX 对 webapi2 (asp.net) controller 的调用,只有 1 个参数就好了(一个 json 对象),但是当尝试发送 2 个参数(一个字符串和一个整数)到一个调用时,其他所有参数都保留一样,我明白了

No HTTP resource was found that matches the request URI找不到与请求 URI 匹配的 HTTP 资源

error in the browser console.浏览器控制台中的错误。 I believe I've tried every combination I can think of to get 2 parameters to pass, but always end up with the same error message: I'm not sure of the correct format for the data, in javascript - I thought I made a JSON object. but did not, I've quoted, unquoted, and tried every combination I can think of.我相信我已经尝试了所有我能想到的组合来传递 2 个参数,但总是以相同的错误消息结束:我不确定数据的正确格式,在 javascript - 我以为我做了一个JSON object。但没有,我已经引用、未引用并尝试了我能想到的每一种组合。 but no joy.但没有快乐。 Does ASP?Net WebAPI2 not accept more than 1 parameter, (I'm converting ASMX from an old site to api controllers and am stuck on 1 particular one that takes 2 parameters - works fine for ASMX. but webapi doesn't seem to recognize the signature). ASP?Net WebAPI2 不接受超过 1 个参数,(我正在将 ASMX 从旧站点转换为 api 控制器,并且卡在 1 个采用 2 个参数的特定控制器上 - 适用于 ASMX。但 webapi 似乎无法识别签名)。

web method in C# (i've tried the post, put and delete verbs - no joy) C# 中的 web 方法(我试过 post、put 和 delete 动词——不开心)

    [Route("api/DeleteUserSearch")]
    [HttpPost]
    [Authorize(Roles = "admin,paid,vendor,visitor")]
    public async Task<IHttpActionResult> DeleteUserSearch(string userid, int usersearchidx)
    {
        int retval = 0;
        if (IsValidUserId(userid))
        {
            retval = (await userSearch_Data.DeleteSavedSearchAsync(userid, usersearchidx)).xToInt();
        }
        return Ok(retval);
    }

The AJAX call: (one version that worked with ASMX) AJAX 电话:(一个与 ASMX 一起工作的版本)

function deleteUserSearch(uid, sid) {
$.ajax({
    url: '../../api/DeleteUserSearch',
    dataType: 'json',
    method: 'post',
    data: { userid:  uid , usersearchidx : sid },
    success: function (data) {
        //refresh searches dropdown
        ShowSuccessMsg('Your search has been deleted.');
        $('#SSPopup').modal('hide');
        RetrieveSearchesDD(uid, "#ddlSavedSearches", false, "")
    },
    error: function (err) {
        console.log('Error (deleteUserSearch): ' + JSON.stringify(err, null, 2));
    }
});
};

This works for all other calls with 1 parameter (any object), but does not for more than one.这适用于具有 1 个参数(任何对象)的所有其他调用,但不适用于多个参数。 What am I doing wrong here?我在这里做错了什么?

Full Error in the Console: (it's obviously a signature problem - the URI is correct).控制台中的完整错误:(这显然是一个签名问题 - URI 是正确的)。

Error (deleteUserSearch): {
  "readyState": 4,
  "responseText": "{\"Message\":\"No HTTP resource was found that matches the request URI 'https://localhost:44371/api/DeleteUserSearch'.\",\"MessageDetail\":\"No action was found on the controller 'SavedSearches' that matches the request.\"}",
  "responseJSON": {
    "Message": "No HTTP resource was found that matches the request URI 'https://localhost:44371/api/DeleteUserSearch'.",
    "MessageDetail": "No action was found on the controller 'SavedSearches' that matches the request."
  },
  "status": 404,
  "statusText": "error"
}

Solution1解决方案1

Get data as one object and one parameter from form 从表单中获取数据作为一个 object 和一个参数

When you are passing data as an object like { userid: uid, usersearchidx: sid } you need some changes in your Controller and Action当您将数据作为 object 传递时,例如{ userid: uid, usersearchidx: sid }您需要对ControllerAction进行一些更改

public class Parameter { public int UserId { get; set; } public int UserSearchIdX { get; set; } } public async Task<IHttpActionResult> DeleteUserSearch([FromForm] Parameter param) { // Your code }

Solution2解决方案2

Get data as two parameters separately 分别获取数据作为两个参数

If you can't change the old code too much and you want to get two parameters separately, then you can do it like this: There is no change in your API:如果不能对旧代码改动太多,想分别获取两个参数,那么可以这样: 你的API没有变化:

function deleteUserSearch(uid, sid) {
  $.ajax({
    url: '../../api/DeleteUserSearch?userId=' + uid + '&userSearchIdX=' + sid,
    dataType: 'json',
    method: 'post',
    //data: { userid: uid, usersearchidx: sid },
    success: function (data) {
        alert("Success");
    },
    error: function (err) {
        console.log('Error');
    }
  });
}

And you can send your parameters like a query string:您可以像查询字符串一样发送参数:

 function deleteUserSearch(uid, sid) { $.ajax({ url: '../../api/DeleteUserSearch?userId=' + uid + '&userSearchIdX=' + sid, dataType: 'json', method: 'post', //data: { userid: uid, usersearchidx: sid }, success: function (data) { alert("Success"); }, error: function (err) { console.log('Error'); } }); }

OK.好的。 Got it figured out.明白了。 WebApi can only handle one parameter, but it can be anything (an object). WebApi 只能处理一个参数,但它可以是任何东西(一个对象)。 Because this is DotNetFW 4.72, the [Form] decorator won't work (DotNetCore only), so I figured I'd just create a JSON object in Javascript and match it with an object in C#.因为这是 DotNetFW 4.72,[Form] 装饰器不起作用(仅限 DotNetCore),所以我想我只是在 Javascript 中创建一个 JSON object 并将其与 C# 中的 object 匹配。

(I have a class/model called UserSearch with the properties UserId and UserSearch_Idx) (我有一个名为 UserSearch 的类/模型,其属性为 UserId 和 UserSearch_Idx)

So the working version code is as follows:所以工作版本代码如下:

    [Route("api/DeleteUserSearch")]
    [HttpDelete]
    [Authorize(Roles = "admin,paid,vendor,visitor")]
    public async Task<IHttpActionResult> DeleteUserSearch(UserSearch p)
    {
        int retval = 0;
        if (IsValidUserId(p.UserId))
        {
            retval = (await userSearch_Data.DeleteSavedSearchAsync(p.UserId, p.UserSearch_Idx)).xToInt();
        }
        return Ok(retval);
    }

On the client side, it's straightforward: Just create a JSON object and assign it's properties.在客户端,它很简单:只需创建一个 JSON object 并为其分配属性。 Code on that end looks like so:那一端的代码如下所示:

function deleteUserSearch(uid, sid) {
    var uSearch = {};
    uSearch.UserId = uid;
    uSearch.UserSearch_Idx = sid;

    $.ajax({
        url: '../../api/DeleteUserSearch',
        dataType: 'json',
        method: 'delete',
        data: uSearch,
        success: function (data) {
            //refresh searches dropdown
            ShowSuccessMsg('Your search has been deleted.');
            $('#SSPopup').modal('hide');
            RetrieveSearchesDD(uid, "#ddlSavedSearches", false, "")
        },
        error: function (err) {
            console.log('Error (deleteUserSearch): ' + JSON.stringify(err, null, 2));
        }
    });
};

Thank you Saeid for the tip (Core has a built in object representing the form data - which is nice)!谢谢 Saeid 的提示(Core 有一个内置的 object 表示表单数据 - 这很好)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM