user1166905
user1166905

Reputation: 2622

WebApi passed data is null

Controller code:

[HttpPost]
public void UpdateClient(Client client)
{  
   // Rest of code
}

Client code:

 $.ajax({
            url: "api/client/UpdateClient",
            type: 'post',
            contentType: 'application/json',
            data: "{client: " + ko.toJSON(model.selectedClient()) + "}",
            success: function (result) {
                getClients();
                $("#loader").hide();
            },
            failure: function (result) {
                alert(result.d);
                $("#loader").hide();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An error occurred, please try again.");
                $("#loader").hide();
            }
        });

For whatever reason the parameter 'client' is always null despite checking that model.selectedClient() is ok and the ko.toJSON is working.

Upvotes: 1

Views: 408

Answers (1)

Maggie Ying
Maggie Ying

Reputation: 10175

I don't think you need to adding the 'client' padding to your data. Try setting data to: ko.toJSON(model.selectedClient())

The 'client' parameter got model bound correctly for me when my Client class looks like this:

public class Client
{
    public string Name { get; set; }
    public string Company { get; set; }
}

... and my ajax looks like this:

        $.ajax({
            url: "api/values/UpdateClient",
            type: "post",
            contentType: 'application/json',
            data: "{ 'Name': 'John', 'Company': 'ABC'}"
        });

Upvotes: 3

Related Questions