Posting data from jquery ajax call to MVC4 controller: data posted is empty

Say you want to create a new contact from an ajax call and have somthing like that:


var theContact = {
lastname: 'Smith',
firstname: 'John'
};
var theData = JSON.stringify(theContact);
$.ajax({
type: "POST",
url: "/contacts/create",
contentType: "application/json; charset=utf-8",
data: theData,
dataType: "json",
success: managesuccess
});

Then on the server, you carefully create your Contact class and the controller, paying attention to giving property names that are identical on client and server:


public class Contact
{
public string lastname;
public string firstname;
}

[System.Web.Mvc.HttpPost]
public string Create(Contact newContact)
{
// Logic
}

Only to realize that while the data is correctly posted from the client, on the server newContact properties stay desperately empty. Well, stop tearing you hair out, all you have to do is to follow best practice and adapt your Contact class by adding get/set! Like this:


public class Contact
{
public string lastname { get; set; }
public string firstname { get; set; }
}

And your data gets correclty posted, what a relief…

Leave a Reply

Your email address will not be published. Required fields are marked *