Reputation: 464
I'm setting a Person() object to a couple of ko.observables and trying to pass it into my ajax call. On the other side, a web API controller its coming over as null.
This is how I'm data-binding to the ko.observables:
<label>First Name</label>
<input type="text" class="form-control margin-bottom-20" data-bind="text: firstname">
<label>Last Name</label>
<input type="text" class="form-control margin-bottom-20" data-bind="text: lastname">
<label>Email Address <span class="color-red">*</span></label>
<input type="text" class="form-control margin-bottom-20" data-bind="text: email">
my .js that is suppose to pick up the ko.observable values but isn't:
var firstname = ko.observable();
var lastname = ko.observable();
var email = ko.observable();
var password = ko.observable();
function submitclicked() {
insertNewUser();
ko.applyBindings(firstname);
ko.applyBindings(lastname);
ko.applyBindings(email);
ko.applyBindings(password);
};
function Person() {
this.FirstName = firstname();
this.LastName = lastname();
this.Email = email();
this.Password = password();
}
function insertNewUser() {
var person = new Person();
$.ajax({
url: "/api/Reg",
type: 'post',
data: JSON.stringify(person),
contentType: "application/json; charset=utf-8",
success: function (result) {
person(result);
}
})
My controller which is somehow not pulling in that "person" object properly. it gets the objects but all of the values are null (even though the text inputs do have text) First_Name = null, Last_Name = null, Email = null, Password = null
public void addUser(Person item)
{
var db = new MyEntities();
try
{
User record = new User()
{
First_Name = item.FirstName,
Last_Name = item.LastName,
Email = item.Email,
Password = item.Password
};
db.User.Add(record);
db.SaveChanges();
Anyone notice where I've messed it up?
EDIT: cleaned up the example a bit.
Upvotes: 0
Views: 267
Reputation: 17554
Use ko.toJSON
it will correctly serialize the observables to plain JSON data
Also you model definition is strange. To define the observables outside of the constructor, this mean that you cant have more than one instance of the Person object
Upvotes: 0
Reputation: 2405
public ..... Post([FromBody]objClass obj)
var thing=obj.property;
Also you cant post an object (it needs to be real data) , see Json stringify try this thread How to JSON.stringify and JSON.parse without getting an empty object?
Upvotes: 1