1

Closed

WebAPI should support $.post for arrays of objects (binding to List<>)

description

Currently, WebAPI doesn't support binding to a signature with a List<> from $.post in jQuery.

Example endpoint:
public void AddFeedItems(List<FeedItemEntry> feedItemsToAdd) {

Where FeedItemEntry is:

public class FeedItemEntry {
    public string FeedUrl { get; set; }
    public string FeedItemLink { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}
$.post requests look like this:

feedItemsToAdd[0][FeedUrl]=hi&feedItemsToadd[0][Title]=hi&…..&feedItemsToAdd[1][FeedUrl]=hi….

and this will fail to model bind (the variable will simply be null).

Here's some quick JS code that hits the endpoint for a quick repro:


var newFeedItems = new Array();
            newFeedItems.push({ FeedUrl: 'hi', FeedItemLink: 'hi', Title: 'hi', Description: 'hi'});
           $.post('/api/Feed/TestEndPoint', { feedItemsToAdd: newFeedItems }, function (data) {
           });
Closed Jun 2, 2012 at 12:25 AM by bhaveshc
Verified that you can pass the object without any prefix by something like following.
$.post('/api/Feed/TestEndPoint', { '': newFeedItems }, function (data) {

This is an easy workaround so this shouldn't be an issue.

comments

bhaveshc wrote May 23, 2012 at 11:43 PM

If the request content were as follows, it would work fine

[0][FeedUrl]=hi&[0][Title]=hi&…..&[1][FeedUrl]=hi…. (not prefixed by 'feedItemsToadd')

However, there is no way of making jQuery generate above format and with the given format, there is no way to make it work (like wrapping the model type). So we should consider fixing this.

yaohuang wrote May 31, 2012 at 12:00 AM

This is by design given that we support one object in the body and the body should contain the object directly without the prefix.
This is consistent with how we handle other formats such as JSON. For instance, Post([FromBody] string content) would expect just "post content" in the body instead of {content : "post content"}.

You should be able to post without any problem if you get rid of the prefix 'feedItemsToAdd':

var newFeedItems = new Array();
            newFeedItems.push({ FeedUrl: 'hi', FeedItemLink: 'hi', Title: 'hi', Description: 'hi'});
           $.post('/api/Feed/TestEndPoint', { '': newFeedItems }, function (data) {
           });