我正在尝试使用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)
{定制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
}
}自定义ModelBinder被正确调用,但Request.InputStream为空,因此没有数据可绑定到PatientFilter对象。
任何想法都很感谢。克里斯
发布于 2009-06-24 17:43:30
对此的一些思考
[DataContract]属性。我不确定它是否会序列化$.ajax()调用。我原以为data选项只接受一个对象,而不是JSON字符串。在查看documentation之后,我会尝试将processData选项设置为false。数据选项还有一个有趣的描述:
要发送到服务器的
数据。它将转换为查询字符串(如果还不是字符串)。它被附加到GET-requests的url中。请参见processData选项以防止此自动处理。对象必须是键/值对。如果value是数组,jQuery将序列化具有相同键的多个值,即{foo:"bar1","bar2"}变成‘&foo=bar1&foo=bar2’。
https://stackoverflow.com/questions/1039105
复制相似问题