MVC ajax json post到控制器操作方法。

时间:2022-10-08 09:40:39

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 * post here .

我试图实现对控制器动作方法的JQuery AJAX调用,该方法包含一个复杂的对象作为参数。我已经阅读了很多博客,并尝试了一些从这些博客中学习到的技巧。我构建我的最佳尝试代码的关键post(以下)是这里的* post。

I want to trigger an asynchronous post, invoked when the user tabs off a field [not a Form save post – as demonstrated in other examples I have found].

我想要触发一个异步post,当用户在一个字段(而不是表单保存post)上制表时调用,正如我在其他示例中发现的那样)。

My intention is to:

我的目的是:

  • Instantiate an object on the client [not the ViewModel which provides the type for the View];
  • 在客户机上实例化一个对象[不是提供视图类型的ViewModel];
  • Populate the object with data from several fields in the view;
  • 用视图中几个字段的数据填充对象;
  • Convert this object to JSON;
  • 将该对象转换为JSON;
  • Call the controller action method using the jQuery.Ajax method, passing the JSON object.
  • 使用jQuery调用控制器操作方法。Ajax方法,传递JSON对象。

The results will be returned as a JSON result; and data will be loaded into fields in the view depending on results returned.

结果将作为JSON结果返回;根据返回的结果,数据将被加载到视图中的字段中。

The problems are:

的问题是:

  • If the action method is attributed with the HttpPost attribute, the controller Action method is not invoked (even though the AJAX call type is set to ‘POST’).
  • 如果操作方法被赋予HttpPost属性,则不会调用控制器操作方法(即使AJAX调用类型设置为“POST”)。
  • If the action method isattributed with HttpGet, the values of properties of the parameter are null
  • 如果操作方法被HttpGet赋值,则参数的属性值为null
  • The ReadObject method throws the error: "Expecting element 'root' from namespace ''.. Encountered 'None' with name 'namespace'".
  • ReadObject方法抛出错误:“期望元素的根来自名称空间”。遇到名称为“名称空间”的“None”。

Hopefully someone can help. Thanks. Code below:

希望有人可以帮助你。谢谢。下面的代码:

Client js file

客户机js文件

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

3 个解决方案

#1


32  

Below is how I got this working.

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

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,以便运行时能够解析请求中的对象。

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[我知道有一种方法可以绑定一个对象,而不是默认的ViewModel对象,但最终只是为我的需要填充必要的属性,因为我无法让它工作]

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

The JQuery script used to call this action method:

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

#2


4  

This blog post directly addresses your problem.

这篇博客文章直接解决了你的问题。

It uses a technique without the need for additional JSON client libraries. It introduces a really simple jQuery plugin that will help you do the trick.

它使用的技术不需要额外的JSON客户端库。它引入了一个非常简单的jQuery插件,可以帮助您实现这一功能。

#3


0  

What version of asp.net mvc are you using? Posting json objects to strongly typed controller actions just got added into ASP.NET MVC 3 Beta 1. This article explains a workaround using model binders for asp.net mvc 2 and info on how it works in MVC 3.

你使用的是哪个版本的asp.net mvc ?将json对象发布到强类型的控制器操作中只是添加到ASP中。NET MVC 3 Beta 1。本文解释了如何使用asp.net mvc 2的模型绑定,以及如何在mvc 3中工作的信息。

#1


32  

Below is how I got this working.

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

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,以便运行时能够解析请求中的对象。

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[我知道有一种方法可以绑定一个对象,而不是默认的ViewModel对象,但最终只是为我的需要填充必要的属性,因为我无法让它工作]

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

The JQuery script used to call this action method:

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

#2


4  

This blog post directly addresses your problem.

这篇博客文章直接解决了你的问题。

It uses a technique without the need for additional JSON client libraries. It introduces a really simple jQuery plugin that will help you do the trick.

它使用的技术不需要额外的JSON客户端库。它引入了一个非常简单的jQuery插件,可以帮助您实现这一功能。

#3


0  

What version of asp.net mvc are you using? Posting json objects to strongly typed controller actions just got added into ASP.NET MVC 3 Beta 1. This article explains a workaround using model binders for asp.net mvc 2 and info on how it works in MVC 3.

你使用的是哪个版本的asp.net mvc ?将json对象发布到强类型的控制器操作中只是添加到ASP中。NET MVC 3 Beta 1。本文解释了如何使用asp.net mvc 2的模型绑定,以及如何在mvc 3中工作的信息。