I am trying to achieve a JQuery AJAX call to a controller action method that contains a complex object as a parameter. I have read plenty blogs and tried several techniques learned from these. The key post on which I have constructed my best attempt code (below) is the stackoverflow post here .
我想触发异步POST,在用户按Tab键关闭字段时调用[不是表单保存POST-正如我发现的其他示例中所演示的那样].
我的意图是:
- 在客户机上实例化一个对象[而不是为视图提供类型的ViewModel];
- 使用视图中多个字段的数据填充对象;
- Convert this object to JSON;
- 使用jQuery.Ajax方法调用控制器操作方法,传递JSON对象.
结果将作为JSON结果返回;数据将根据返回的结果加载到视图中的字段中.
The problems are:
- 如果action方法的属性是HttpPost属性,则不会调用控制器action方法(即使AJAX调用类型设置为"POST").
- If the action method isattributed with HttpGet, the values of properties of the parameter are null
- The ReadObject method throws the error: "Expecting element 'root' from namespace ''.. Encountered 'None' with name 'namespace'".
希望有人能帮上忙.谢谢.代码如下:
Client js file
var disputeKeyDataObj = {
"InvoiceNumber": "" + $.trim(this.value) + "",
"CustomerNumber": "" + $.trim($('#CustomerNumber').val()) + ""
};
var disputeKeyDataJSON = JSON.stringify(disputeHeadlineData);
$.ajax({
url: "/cnr/GetDataForInvoiceNumber",
type: "POST",
data: disputeKeyDataJSON,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: EnrichedDisputeKeyData(result)
});
Action Filter and class for the type associated with the Action method parameter
[DataContract]
public class DisputeKeyData
{
[DataMember(Name = "InvoiceNumber")]
public string InvoiceNumber { get; set; }
[DataMember(Name = "CustomerNumber")]
public string CustomerNumber { get; set; }
}
Action method on the controller
//[HttpPost]
[ObjectFilter(Param = "disputeKeyData", RootType = typeof(DisputeKeyData))]
public ActionResult GetDataForInvoiceNumber(DisputeKeyData disputeKeyData)
{
//Blah!
//....
return Json(disputeKeyData, JsonRequestBehavior.AllowGet);
}