0

I'm getting null for the controller parameter. I am posting data as I can see it in Chrome Developer tools. I have a Person model in MVC that matches the Person model below. This is my ViewModel :

 function Person(data) {
    this.FirstName = ko.observable(data.FirstName);
    this.LastName = ko.observable(data.LastName);
    this.Id = ko.observable(data.Id);

    this.fullName = ko.computed(function () {
        return this.FirstName() + " " + this.LastName();
    }, this);

}

function PersonViewModel() {
    var self = this;
    self.people = ko.observableArray([]);



    $.getJSON("/api/person/getpeople", function (allData) {
        var mappedTasks = $.map(allData, function (item) { return new Person(item) });
        self.people(mappedTasks);
    });


    self.save = function(){

        $.ajax("/api/person/updateperson", {
            data: ko.toJSON({ people: self.people }),
            type: "post", contentType: "application/json",
            success: function (result) { alert(result) }
        });
    }
}
ko.applyBindings(new PersonViewModel);

API controller:

  [HttpPost]
    public bool UpdatePerson(List<Person> person)
    {
        return mgr.UpdatePerson(person);
    }
2
  • parameter name mismatch person in controller people in js . Commented Apr 16, 2015 at 12:17
  • you can simply try this data: ko.toJSON(self.people ), no need to mention people . cheers Commented Apr 16, 2015 at 12:17

1 Answer 1

1

You need to make sure that the service parameter's names match up with what you're passing.

self.save = function(){

        $.ajax("/api/person/updateperson", {
            data: ko.toJSON({ person: self.people }),
            type: "post", contentType: "application/json",
            success: function (result) { alert(result) }
        });
    }
Sign up to request clarification or add additional context in comments.

6 Comments

The developer tool in Chrome tells me I'm passing: {people: [{FirstName: "Paul", LastName: "Allen", Id: 17, fullName: "Paul Allen"},…]}
Right, but you want to change people: to person: in order to match what the C# method is expecting as a parameter
ok, I changed the code in ajax method to data: ko.toJSON({ person: self.person }), along with the other names of people to person and it is still null. I have <ul data-bind="foreach: person"> <li> <input data-bind="value:fullName" /> </li> </ul> in the html
Hmm, does the data you're passing to UpdatePerson() look the same? What's the C# Person class look like?
I think you have the right idea but maybe some variable names in the Person objects don't line up. Capitalization or types can cause things to choke
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.