Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c# - Posting array of objects with MVC Web API

I have a basic post operation that works on a single object of RecordIem. What I would like to do is do the same action but in bulk by posting an array of requests using the same format.

For instance:

public HttpResponseMessage Post(RecordItem request)
{
    var recordItems = _recorder.RecordItem(request);
    return Request.CreateResponse(HttpStatusCode.OK, recordItems);
}

And when I post the Json:

{
    Id : "7UP24fVkGOxSjrcclghe_mP2-po",
    System : 1,
    Environment : "Production"
}

everything works fine. I would like to post Json similar to:

{
    Id : "7UP24fVkGOxSjrcclghe_mP2-po",
    System : 1,
    Environment : "Production"
},
{
    Id : "ClPE188H4TeD2LbQPeV_EzCsKVM",
    System : 1,
    Environment : "Production",
    Label : "RestTest1"
},
{
    Id : "SAWTMJzm-_AFqoNw70-gLeUzB4k",
    System : 1,
    Environment : "Production"
}

And have a method similar to below pick this up:

public HttpResponseMessage Post(RecordItem[] request)
{
    var recordItems = _recorder.RecordItems(request);
    return Request.CreateResponse(HttpStatusCode.OK, recordItems);
}

I've tried using both the [FromBody] and [ModelBinding] attributes on the array and tried using different types (List, IList, IEnumerable) but to no avail. When using [FromBody] the request parameter is null and when using [ModelBinding] the list is empty. I've tried using both and that doesn't work either.

I'd rather not have to having to resort to looping single posts in my client.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For all that just get an empty array whatever they try, try this:

var request = $.ajax({
  dataType: "json",
  url: "/api/users",
  method: "POST",
  data: { '': postData}
});

The data must be a single anonymous object instead of a raw array.

Info was found here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...