contactmatt
contactmatt

Reputation: 18610

Web API - Simple Post model with collection property is not binding

// Server-side Model to bind

    public class CurrentPipelineRequest
    {
        public List<string> Usernames { get; set; }
    }

// Controller

[HttpPost]
public HttpResponseMessage CurrentPipelineByMilestone(CurrentPipelineRequest currentPipelineRequest)
{
    //.....
}

// Jquery/Ajax

   var model = {
            'Usernames' : JSON.stringify(["me", "you", "I"])
        };
    $.ajax({
        contentType: 'application/json',
        type: 'POST',
        url: 'api/Dashboard/CurrentPipelineByMilestone'
        data: model,
        success: function (data) {
            alert('success');
        }
});

Currently, the controller action parameter "currentPipelineRequest" will be null.

Upvotes: 0

Views: 2152

Answers (3)

Chris Dixon
Chris Dixon

Reputation: 9167

This is actually because you're doing a POST and not sending your model through as a JSON object, so the service can't understand it.

Try this:

var model = {
            'Usernames' : ["me", "you", "I"]
        };

var data = JSON.stringify(model);

$.ajax({
    contentType: 'application/json',
    type: 'POST',
    url: 'api/Dashboard/CurrentPipelineByMilestone'
    data: data,
    success: function (data) {
        alert('success');
    }

});

Upvotes: 0

cuongle
cuongle

Reputation: 75316

You need to stringify the whole model instead of only Usernames:

var model = {
        Usernames : ["me", "you", "I"]
    };

$.ajax({
    contentType: 'application/json',
    type: 'POST',
    url: 'api/Dashboard/CurrentPipelineByMilestone'
    data: JSON.stringify(model),
    success: function (data) {
        alert('success');
});

Upvotes: 2

frictionlesspulley
frictionlesspulley

Reputation: 12388

Binding in ASP.NET Web API is not exactly same as ASP.NET MVC.

However in ASP.NET Web API as the body content is treated a forward-only stream that can only be read once. Hence in case of complex signatures on Actions you need to specify from where you expect the parameters.

if you are getting the parameters form the body change the signature to :

public HttpResponseMessage CurrentPipelineByMilestone(
      [FromBody] CurrentPipelineRequest currentPipelineRequest)

if you are getting the parameters from uri change the signature to :

public HttpResponseMessage CurrentPipelineByMilestone(
      [FromUri] CurrentPipelineRequest currentPipelineRequest)

if you are getting the parameters from uri and body then change the signature to :

public HttpResponseMessage CurrentPipelineByMilestone(
      [ModelBinder] CurrentPipelineRequest currentPipelineRequest)

Here is an article for trying to implement MVC style binding in Web API. Please note that I haven't tried it myself.

Upvotes: 2

Related Questions