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);  
  }  

推荐答案

下面是我是如何让它工作的.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[我知道有一种方法可以绑定默认ViewModel对象以外的对象,但最终只是根据我的需要简单地填充了必要的属性,因为我无法使其工作.]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

用于调用此操作方法的JQuery脚本:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Json相关问答推荐

如何在Power BI中集成API和JSON数据后将数据转换为表?

您可以使用Jolt对JSON执行OR条件吗

如何在PowerShell中扩展JSON中的嵌套数组

如何形成正确的JQ表达式以从JSON文件中获得准确的输出数据?

如何用JQ更改空/布尔/数字的 colored颜色 ?

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

bash用jq获取第二条JSON记录

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

使用 JOLT 将日期格式转换为 JSON

在 json 对象中存储多个键:值对

将 json 转换为 jsonb 安全吗?

从 oracle 数据库中的 json blob 打印值

使用 Groovy 将 XML 转换为 JSON

try 使用 JQ 转换 JSON 中过于复杂的对象数组

JSONPath:查找子项目条件在字符串列表中的项目

Vue 3如何将参数作为json发送到axios get

boost::json::value 的大括号初始化将其从对象转换为数组

N1QL 搜索对象内的某些对象

Golang struct 的 XML 和 JSON 标签?

Volley JsonObjectRequest Post 参数不再起作用