MVC阿贾克斯JSON岗位控制器的操作方法 [英] MVC ajax json post to controller action method

查看:212
本文介绍了MVC阿贾克斯JSON岗位控制器的操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个jQuery AJAX调用包含一个复杂的对象作为参数控制器的操作方法。 我看了很多博客,并试图从这些学到了一些技巧。关键的岗位上,我已经构建了我最好的尝试code(下图)是计算器后<一href="http://stackoverflow.com/questions/560575/asp-net-mvc-how-to-pass-json-object-from-view-to-controller-as-parameter">here 。

我想触发一个异步后,调用用户标签掀起了现场的时候[不是窗体保存后 - 这表现在其它的例子,我发现。

我的目的是:

  • 在客户端[未提供该类型的查看视图模型]上实例化一个对象;
  • 填充从视图中的几个字段数据的对象;
  • 在转换这个对象JSON;
  • 呼叫使用jQuery.Ajax方法控制器的操作方法,传递JSON对象。

结果将返回一个JSON结果;和数据将被装载到根据结果返回的视场。

的问题是:

  • 如果操作方法,是因为与HttpPost属性,该控制器的操作方法不会被调用(即使AJAX调用类型设置为POST)。
  • 如果操作方法isattributed与HTTPGET,参数属性的值都为空
  • 在readObject方法引发错误:从命名空间的期望元素'根'''..遇到无名为'空间'。

希望有人可以提供帮助。谢谢。低于code:

客户端的js文件

  VAR disputeKeyDataObj = {
     InvoiceNumber:+ $ .trim(THIS.VALUE)+,
     CUSTOMERNUMBER:+ $ .trim($('#CUSTOMERNUMBER)VAL())+
  };

  VAR disputeKeyDataJSON = JSON.stringify(disputeHeadlineData);

  $阿贾克斯({
     网址:/ CNR / GetDataForInvoiceNumber
     键入:POST,
     数据:disputeKeyDataJSON,
     数据类型:JSON,
     的contentType:应用/ JSON的;字符集= UTF-8,
     成功:EnrichedDisputeKeyData(结果)
  });
 


行为过滤器和类,以便与行动方法的参数相关联的类型

  [DataContract]
 公共类DisputeKeyData
 {
    [数据成员(NAME =InvoiceNumber)
    公共字符串InvoiceNumber {获得;组; }

    [数据成员(NAME =CUSTOMERNUMBER)
    公共字符串CUSTOMERNUMBER {获得;组; }
 }
 

控制器上操作的方法

  // [HttpPost]
  [ObjectFilter(参数=disputeKeyData,RootType = typeof运算(DisputeKeyData))]
  公众的ActionResult GetDataForInvoiceNumber(DisputeKeyData disputeKeyData)
  {
     //胡说!
     // ....
     返回JSON(disputeKeyData,JsonRequestBehavior.AllowGet);
  }
 

解决方案

下面是我得到了这个工作。

关键的一点是: 我需要使用与视图关联的视图模型,以便在运行时能够解决的对象的要求。

[我知道,有一种方法来绑定对象而不是默认的视图模型对象等,但最终只是填充必要属性,我的需要,因为我无法得到它的工作]

  [HttpPost]
  公众的ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
  {
     VAR invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber,myViewModel.SelectedCompany code);
     返回JSON(invoiceNumberQueryResult,JsonRequestBehavior.DenyGet);
  }
 

用于调用该操作方法的jQuery脚本:

  VAR的RequestData = {
         InvoiceNumber:$ .trim(THIS.VALUE)
         SelectedCompany code:$ .trim($('#SelectedCompany code')VAL())
      };


      $阿贾克斯({
         网址:'/ EN / myController的/ GetDataForInvoiceNumber',
         键入:POST,
         数据:JSON.stringify(的RequestData)
         数据类型:JSON,
         的contentType:应用/ JSON的;字符集= UTF-8,
         错误:函数(XHR){
            警报('错误:'+ xhr.statusText);
         },
         成功:函数(结果){
            CheckIfInvoiceFound(结果);
         },
         异步:真正的,
         过程数据:假的
      });
 

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 .

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].

My intention is to:

  • Instantiate an object on the client [not the ViewModel which provides the type for the View];
  • Populate the object with data from several fields in the view;
  • Convert this object to JSON;
  • Call the controller action method using the jQuery.Ajax method, passing the JSON object.

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

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’).
  • 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'".

Hopefully someone can help. Thanks. Code below:

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

解决方案

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.

[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]

[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:

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

这篇关于MVC阿贾克斯JSON岗位控制器的操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆