[英]Problem passing JSON data using jQuery $.ajax() to .NET MVC Action w/ custom BindingModel
我試圖使用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對象。
任何想法都贊賞。 克里斯
對此有一些想法
[DataContract]
屬性。 我不確定它是否會序列化任何東西 $.ajax()
調用。 我希望數據選項只是一個對象而不是一個JSON字符串。 查看文檔后 ,我會嘗試將processData選項設置為false。 還有一個有趣的數據選項描述:
要發送到服務器的數據。 如果不是字符串,它將轉換為查詢字符串。 它附加到GET請求的URL。 請參閱processData選項以防止此自動處理。 對象必須是鍵/值對。 如果value是一個數組,則jQuery使用相同的鍵序列化多個值,即{foo:[“bar1”,“bar2”]}變為'&foo = bar1&foo = bar2'。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.