将字符串数组作为数据传递给Web API的jQuery AJAX

5
我试图将字符串数组传递给一个接受字符串数组为参数的Web Api方法。以下是我的Web Api方法。
    [HttpGet]
    public string HireRocco(string[] hitList)
    {
        string updateList = string.Empty;
        return updateList;
    }

我的Ajax
var uri = 'http://localhost:16629/api/AssassinApi/HireRocco',
hitList = ['me', 'yourself'];

$.ajax({
    url: uri,
    type: 'GET',
    data: { hitList : hitList },
    cache: false,
    dataType: 'json',
    async: true,
    contentType: false,
    processData: false,
    success: function (data) {
    },
    error: function (data) {
    }
});

上述ajax成功调用了方法,但是< hitList >参数仍为null。我应该如何更改才能将字符串数组传递作为参数。

@Rakesh_Kumar:这是一个GET方法,但是如果我使用POST方法,它也无法解决问题。 - Rahul Chakrabarty
3个回答

4

如果你需要通过HttpGet发送数据,你可以添加[FromUri],然后编辑你的控制器操作如下,你的JavaScript应该仍然可以正常工作:

[HttpGet]
public string HireRocco([FromUri] string[] hitList)
{
    string updateList = string.Empty;
    return updateList;
}

0

移除 contentType: false,然后将 processData 设置为 true,这样它就可以将 postData 添加到您的 URL 中,因为这是 GET 请求的工作方式,否则您将不得不更改您的 API 以接受通过标头设置的 POST 请求。

$.ajax({
    url: uri,
    type: 'GET',
    data: { hitList : hitList },
    cache: false,
    dataType: 'json',
    async: true,
    processData: true,
    success: function (data) {
        console.log(data);
    },
    error: function (data) {
    }
});

0
首先,我建议您使用POST而不是GET。 创建一个JavaScript数组。将数据推入其中。使用JSON.Stringify将其发送到Web API操作方法,然后处理进一步的逻辑。
在Web API中创建一个模型变量,并创建一个列表对象。
以下是代码。
Javascript
var demoarray=[];
demoarray.push({"test1":"hi", "test2":"hello"}); //test1 and test2 are model variable names in web api and hi and hello are their values

你可以使用for循环或其他方法重复该过程以添加多个值。

 $.ajax({
      url:"http://localhost..",
      type: "POST",
      data: JSON.Stringify(demoarray),
      contentType: "application/json",
      success: function(data)
               {
               },
      error: function(data)
             {
             }
       });

WEB API 代码 创建一个模型类和两个属性

public string test1 {get; set;}
public string test2 {get; set;}

控制器代码

[Httppost]
public void actionmethod(List<modelclass> obj)
{
  int i=0;
  for(i=0; i<obj.count; i++)
  {
    //your logic
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接