Web Api Parameter always null

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    data: '=' + encodeURIComponent(request.term),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});

Basically you can have only one parameter of scalar type which is decorated with the [FromBody] attribute and your request needs to use application/x-www-form-urlencoded and the POST payload should look like this:

=somevalue

Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.

You can read more about how model binding in the Web Api works in this article.

But of course this hacking around is a sick thing. You should use a view model:

public class MyViewModel
{
    public string Value { get; set; }
}

and then get rid of the [FromBody] attribute:

public IEnumerable<string> Post(MyViewModel model)
{
    return new string[] { "value1", "value2", model.Value };
}

and then use a JSON request:

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ value: request.term }),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});

Leave a Comment