C# 将字符串数组发布到 Web API 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14208888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:03:14  来源:igfitidea点击:

Post array of strings to web API method

c#javascriptajaxpostasp.net-web-api

提问by Eunyoung Ro

this is my client side ajax call:

这是我的客户端 ajax 调用:

    var list = ["a", "b", "c", "d"];

    var jsonText = { data: list };

    $.ajax({
        type: "POST",
        url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
        data: jsonText,
        dataType: "json",
        traditional: true,
        success: function() { alert("it worked!"); },
        failure: function() { alert("not working..."); }
    });

this is chrome network header:

这是 chrome 网络标题:

Request URL:http://localhost:2538/api/scheduledItemPriceStatus/updateStatusToDelete

Request Method:POST

Request Headersview source

Accept:application/json, text/javascript, */*; q=0.01

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-US,en;q=0.8

Connection:keep-alive

Content-Length:27

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Host:localhost:2538

Origin:http://localhost:2538

Referer:http://localhost:2538/Pricing/ScheduledItemPrices

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11

X-Requested-With:XMLHttpRequest

Form Dataview URL encoded

表单数据视图 URL 编码

data:a
data:b
data:c
data:d

this is my webapi controller method:

这是我的 webapi 控制器方法:

public HttpResponseMessage UpdateStatusToDelete(string[] data)

result:

结果:

when I debug, the data parameter in UpdateStatusToDelete returns {string[0]}instead of data:a data:b data:c data:d

当我调试时,UpdateStatusToDelete 中的 data 参数返回{string[0]}而不是 data:a data:b data:c data:d

What am I doing wrong? Any help is really appreciated.

我究竟做错了什么?任何帮助都非常感谢。

回答by Cris

use var jsonText = { data: JSON.stringify(list)}

var jsonText = { data: JSON.stringify(list)}

回答by Mark Berryman

For passing simply types, the data to post must take the form of a name value pair with the name portion being an empty string. So you need to make the Ajax call like so:

为了传递简单的类型,要发布的数据必须采用名称值对的形式,名称部分为空字符串。所以你需要像这样进行 Ajax 调用:

$.ajax({
  type: "POST",
  url: "/api/values",
  data: { "": list },
  dataType: "json",
  success: function() { alert("it worked!"); },
  failure: function() { alert("not working..."); }
});

Additionally, on your Web API action, annotate it w/ the [FromBody] attribute. Something like:

此外,在您的 Web API 操作上,使用 [FromBody] 属性对其进行注释。就像是:

public void Post([FromBody]string[] values)

That should do the trick.

这应该够了吧。

回答by Shaulian

You should pass the listitself, and not any other object wrapping it.

您应该传递它list本身,而不是任何其他包装它的对象。

E.g. pass the following:

例如通过以下:

var list = ["a", "b", "c", "d"];

in

$.ajax({
        type: "POST",
        url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
        // Pass the list itself
        data: list, 
        dataType: "json",
        traditional: true,
        success: function() { alert("it worked!"); },
        failure: function() { alert("not working..."); }
    });

Your method signature on server is correct.

您在服务器上的方法签名是正确的。

回答by Gaurav Shah

use the method above to send array as suggested by cris in your jquery ajax call. JSON data is usually in key value pair.

使用上面的方法按照 cris 在 jquery ajax 调用中的建议发送数组。JSON 数据通常在键值对中。

  var tmp = [];
  tmp.push({
  //this is the key name 'a'  "a": "your value", //it could be anything here in 
   //string format.
    "b": "b",
    "c": "c",
    "d": "d"
   });

 { data: JSON.stringify(tmp);} 

You can also accomplish above by using two dimensional array

您也可以通过使用二维数组来完成上述操作

Additionally do this in the webapi project.

另外在 webapi 项目中执行此操作。

under the models folder in your web api project create a class file. Possibly class1.cs.

在 web api 项目的模型文件夹下创建一个类文件。可能是class1.cs

Create 4 properties

创建 4 个属性

public string a {get; set;}
public string b {get; set;}
public string c {get; set;}
public string d {get; set;}

Now do this in your controller

现在在您的控制器中执行此操作

using projectname.models

[HttpPost]
public return-type actionname(List<Class1> obj)
{
  //Further logic goes here
} 

I am sure this will work.

我相信这会奏效。

回答by Sergey

Setting the dataType won't help you.

设置 dataType 对您没有帮助。

This is how I do it :

这就是我的做法:

var SizeSequence = {};
SizeSequence.Id = parseInt(document.querySelector("dd#Sequence_Id").textContent);
SizeSequence.IncludedSizes = [];
var sizes = document.querySelectorAll("table#IncludedElements td#Size_Name");
// skipping the first row (template)
for (var i = 1, l = sizes.length ; i != sizes.length ; SizeSequence.IncludedSizes.push(sizes[i++].textContent));

$.ajax("/api/SizeSequence/" + SizeSequence.Id, { 
     method: "POST",
     contentType: "application/json; charset=UTF-8",
     data: JSON.stringify(SizeSequence.IncludedSizes), 
...

The Server Part

服务器部分

// /api/SizeSequence/5
public async Task<IHttpActionResult> PostSaveSizeSequence(int? Id, List<String> IncludedSizes)
    {
        if (Id == null || IncludedSizes == null || IncludedSizes.Exists( s => String.IsNullOrWhiteSpace(s)))
            return BadRequest();
        try
        {

            await this.Repo.SaveSizeSequenceAsync(Id.Value, IncludedSizes );
            return Ok();
        }
        catch ( Exception exc)
        {
            return Conflict();
        }
    }

References

参考

jQuery.ajax()

jQuery.ajax()

回答by Stelian Matei

In the backend, you could use FormDataCollection.GetValues(string key)to return an array of strings for that parameter.

在后端,您可以使用FormDataCollection.GetValues(string key)返回该参数的字符串数组。

public HttpResponseMessage UpdateStatusToDelete(FormDataCollection formData) {
    string[] data = formData.GetValues("data");
    ...
}