As part of an ASP.NET MVC4 Web Application, I have a client-side Javascript Viewmodel with a "Save" function that POSTs to a controller:
PatientViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/Patient/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.patientViewModel != null) {
ko.mapping.fromJS(data.patientViewModel, {}, self);
}
}
});
}
}
Upon "success", the client expects data that contains the original viewmodel that is re-mapped using KnockoutJS. The following server-side viewmodel is the blueprint for the mapping:
public class PatientViewModel
{
public int PatientId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime? DOB { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string PhoneAlternate { get; set; }
}
Notice the DOB property with a type of DateTime?
. This is set on the client along with all the other properties.
The controller that receives the viewmodel from the client creates a new "Patient" that is saved to a database.
public JsonResult Save(PatientViewModel patientViewModel)
{
Patient patient = new Patient();
patient.LastName = patientViewModel.LastName;
patient.FirstName = patientViewModel.FirstName;
patient.DOB = patientViewModel.DOB;
patient.Address = patientViewModel.Address;
patient.City = patientViewModel.City;
patient.State = patientViewModel.State;
patient.Zip = patientViewModel.Zip;
patient.Phone = patientViewModel.Phone;
patient.PhoneAlternate = patientViewModel.PhoneAlternate;
_patientContext.Patients.Add(patient);
_patientContext.SaveChanges();
return Json(new { patientViewModel });
}
When the controller returns its "JsonResult", the result contains the original viewmodel with the DOB (DateTime?) property set to "Now" instead of the date and time it received from the client.
The other properties remain the same as when the viewmodel was originally sent to the controller. I've debugged and stepped through the code. The DOB property holds the date sent to it at the point of return Json(new {patientViewModel} );
, and changes to "Now" as soon as it hits the success
method in the client-side viewmodel.
What am I missing?