I am trying to pass JSON data from the client browser to an ASP.NET MVC Action using jQuery $.ajax() and bind it to a .NET class using a custom ModelBinder.
THE CLIENT JAVASCRIPT:
$('#btnPatientSearch').click(function() {
var patientFilter = {
LastName: 'Flinstone',
FirstName: 'Fred'
};
var jsonData = $.toJSON(patientFilter);
$.ajax({
url: '/Services/GetPatientList',
type: 'GET',
cache: false,
data: jsonData,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 10000,
error: function() {
alert('Error loading JSON=' + jsonData);
},
success: function(jsonData) {
$("#patientSearchList").fillSelect(jsonData);
}
});
THE .NET CLASS FOR THE JSON DATA
[ModelBinder(typeof(JsonModelBinder))]
public class PatientFilter
{
#region Properties
public string IDNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SSN { get; set; }
public DateTime DOB { get; set; }
#endregion
}
THE MVC ACTION
public JsonResult GetPatientList(iPatientDoc.Models.PatientFilter patientFilter)
{
THE CUSTOM MODELBINDER
public class JsonModelBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext");
var serializer = new DataContractJsonSerializer(bindingContext.ModelType);
return serializer.ReadObject(controllerContext.HttpContext.Request.InputStream);
#endregion
}
}
The custom ModelBinder is called correctly, yet the Request.InputStream is empty so there is no data to bind to the PatientFilter object.
Any thoughts appreciated. Chris