graemegets
graemegets

Reputation: 265

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!

This is a simple JS script that Posts data back to ApiController.

function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
 //self = this;   
    $.ajax({
        //dataType: "json",
        type: "POST",
        url: self.url,
        data: JSON.stringify(self.parameterObject),
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            self.callbackfunction.call(this, data);
        },//self.GotData,
        error: function (xhRequest, ErrorText, thrownError)
        {
            alert("error : " + ErrorText)
        },
        complete: function () {},
    })


}

}

The data being sent (parameterObject) is simply

var postData = {
            clientId: id
        }

The c# code in the controller is :

 public class ClientPostObject
{
    public string clientId;
}

public class ClientDetailController : ApiController
{

    [HttpPost]
    public ClientDetailWidgetData GetClient(ClientPostObject clientObject)

    {
        return new ClientModel().GetClientDetail(clientObject.clientId);
    }
}

In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?

No matter what I try (and I'be been through many suggestions on the web), the post data is not there.

Sure its something simple.... Thanks in advance.

Upvotes: 2

Views: 1071

Answers (2)

Tieson T.
Tieson T.

Reputation: 21191

Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:

[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
    return new ClientModel().GetClientDetail(clientId);
}

I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.

Upvotes: 1

peterm
peterm

Reputation: 92785

Try to ditch contentType and don't stringify data:

$.ajax({
    type: "POST",
    url: self.url,
    data: self.parameterObject,
    success: function (data) {...},
    ...
});

Upvotes: 0

Related Questions