使用jQuery $ .ajax()将JSON数据传递给带有自定义BindingModel的.NET MVC Action的问题
我试图使用jQuery $ .ajax()将JSON数据从客户端浏览器传递到ASP.NET MVC Action,并使用自定义ModelBinder将其绑定到.NET类。
客户端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); } });
JSON数据的.NET类
[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 }
MVC行动
public JsonResult GetPatientList(iPatientDoc.Models.PatientFilter patientFilter) {
定制模型绑定器
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 } }
自定义ModelBinder被正确调用,但Request.InputStream为空,因此没有数据可以绑定到PatientFilter对象。
任何想法都赞赏。 克里斯
对此的一些想法
- 您使用GET请求。 我认为请求体对于GET总是空的
- 您的PatientFilter类没有
[DataContract]
属性。 我不确定它是否会序列化任何东西 - 我不确定您的
$.ajax()
调用。 我希望数据选项只是一个对象而不是一个JSON字符串。 查看文档后 ,我会尝试将processData选项设置为false。
数据选项还有一个有趣的描述:
要发送到服务器的数据。 如果不是字符串,它将转换为查询字符串。 它附加到GET请求的URL。 请参阅processData选项以防止此自动处理。 对象必须是键/值对。 如果value是一个数组,则jQuery使用相同的键序列化多个值,即{foo:[“bar1”,“bar2”]}变为’&foo = bar1&foo = bar2’。