I've been trying this out for about a day already and looked through multiple questions and answers and still unable to solve this.
Regardless, my name value will always be null or end up with a bad request error 400. Really would appreciate if someone could tell me what I'm doing wrong here.
Javascript:
var myPerson = {};
myPerson.name = "Brandon";
function createObject() {
$.ajax({
contentType: "application/json;charset=utf-8",
dataType: 'json',
type: 'POST',
url: '/Person/CreatePerson',
data: JSON.stringify(myPerson),
success: function (response) {
alert(JSON.stringify(myPerson);
}, error: function (e) {
alert(e.responseText);
}
})
}
Controller:
[HttpPost]
public ActionResult CreatePerson(string name)
{
Person person = new Person();
person.Name = name;
_context.Person.Add(person);
_context.SaveChanges();
return Json(person);
}
contentType: 'application/json', there's no real need for it. Just send the data in the normal form-encoded format[object Object]because it's an object...alert(JSON.stringify(response));will give you a better idea of the response data.responseis a JSON object, not plain text, so you can't just print it directly