After submitting an ajax call, I have confirmed in the request header that all the json fields have a value. What I do not understand is that when I debug on the server side, only the DateEntered field has a value (parsed into a DateTime object). When I put the same information in using Postman, it works just fine on the server (all the fields have a value).
Controller method:
[HttpPost]
public JsonResult SaveJobApplication(ApplicationFormObject jobApplicationObject)
{
return Json(_jobApplicationController.SaveJobApplication(jobApplicationObject), JsonRequestBehavior.AllowGet);
}
Ajax call:
$.ajax({
url: 'http://myurl.com/SaveJobApplication',
data: JSON.stringify(applicationInfo),
contentType: 'application/json',
type: 'POST'
}).done(function(message) {
// do some stuff
});
Here is the context:
The ajax request is coming from a different origin 'http://somedomain.com' than my server origin 'http://myserverdomain.com'. I have implemented CORS in the Web.Config file like so:
...
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
...
This has been tested and it is working fine (My server is able to grant ajax requests from other origins).
The json object that I am submitting is like this:
var applicationInfo = {
FirstObject: {
'NameFirst': 'blah blah',
'NameLast': 'blah blah blah',
'DateEntered': '2012-5-5'
},
SecondObject: {
'LastJob': 'blah blah',
'ReasonQuit': 'blah blah blah'
}
}
The class/objects on the server are like this:
// Object that ajax is utilizing
public class ApplicationFormObject
{
public FirstObject FirstObject { get; set; }
public SecondObject SecondObject { get; set; }
}
public class FirstObject
{
public string NameFirst { get; set; }
public string NameLast { get; set; }
public DateTime? DateEntered{ get; set; }
}
public class SecondObject
{
public string LastJob { get; set; }
public string ReasonQuit { get; set; }
}
Important Information
The json object that I am sending is created dynamically. I actually loop through the form elements via ajax .each. For each element I am adding it to an object like so:
var applicationInfo = {};
$('form input, form select').each(function() {
var that = $(this);
if(isValid(that)) {
applicationInfo["'" + that.attr('id') + "'"] = that.val();
}
});
When I look at the request header, it shows the JSON as being in such format:
{
...
'demoObject': "Value of demo object"
...
}
However, when I test it on Postman, the object is not created dynamically. I explicitly fill in the json object one by one for test data. When I look at the request header for this method, it shows the JSON as being in such format:
{
...
demoObject: "Value of demo object"
...
}
the difference being that the second example does not have single quotes, and the first one does. Hope this information makes sense. Please let me know how I can clarify.