MVC ajax json post to controller action method

前端 未结 1 1974
南方客
南方客 2020-11-28 08:59

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

相关标签:
1条回答
  • 2020-11-28 09:39

    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
          });
    
    0 讨论(0)
提交回复
热议问题