0

I need to take in a collection of MyObject on my webApi controller:

[RoutePrefix("api/DoStuffApi")]
public class DoStuffApiController : ApiController
{
    [Route("Update/")]
    public HttpStatusCode Update(IEnumerable<MyObject> requests)
    {
        //DO STUFF
    }
}

I would need to use the FromBody parameter attribute to get the list normally:

    [Route("Update/")]
    public HttpStatusCode Update([FromBody] IEnumerable<MyObject> requests)
    {
        //DO STUFF
    }

Is this better than taking in an object with a collection on it?

    [Route("Update/")]
    public HttpStatusCode Update(MyRequestObject request)
    {
        //DO STUFF
    }

    public class MyRequestObject
    {
        public IEnumerable<MyObject> requests {get;set;}
    }

On the second example I can create a JavaScript object or an Angular module that matches the parameter and pass it into the post call on angular.

 .factory('setSomething', [
        '$http',
        function($http) {
            return {
                var data = new objectsToUpdate(); //my custom object with an array in it
                set: function (customerId) {
                    return $http.post('api/DoStuffApi/Update/', data);
                }
            }
        }
    ]);

I cannot find any information on how to do this type of thing. The route attributes follow this article.

1 Answer 1

1

This just really depends on what your object you want to post looks like. Do you need to send any other data than the array in the POST? If not then using the former solution would be better since otherwise you are just writing useless additional code for you to maintain. So using the former example would be cleaner.

If however you have more data in your post along with the array you should put it all in a special model class in the controller like you do in your second example..

To have angular POST it correctly so the API model binds to the IEnumerable in the first example, you would simply post the array itself instead of having it inside an object.

    function($http) {
        return {
            var data = new objectsToUpdate(); //my custom object with an array in it
            set: function (customerId) {
                return $http.post('api/DoStuffApi/Update/', data.nameOfArray); // Don't post the object, just the array
            }
        }
    }

This should bind to the IEnumerable just fine if the fields in the model and the array have the same names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.