【问题标题】:knockout - pass child array with viewmodel data淘汰赛 - 使用视图模型数据传递子数组
【发布时间】:2015-10-03 01:15:20
【问题描述】:

我有一个如下视图模型:

var viewModel = new function () {

    var self = this;
    self.Id = ko.observable();
     self.currentOrder = {

      orderId: ko.observable(),
      firstCropId: ko.observable(),
      secondCropId: ko.observable(),

      productDataList: ko.observableArray()
  };
       
       
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>

我正在尝试将 viewModel.currentOrder 传递给 MVC 控制器,如下所示:

self.SaveOrder = function () {
      var url = '@Url.Action("SaveOrder", "Orders")';
      $.mobile.loading('show');

      var productInfo = {};

      for (i = 0; i < 3; i++) {
        productInfo = { Id: i, Rate: i + 11, Variable: i + 111 };
        viewModel.currentOrder.productDataList.push(productInfo);
      }


       $.ajax({
          type: 'POST',
          url: url,
          dataType: 'json',
          data: viewModel.currentOrder,
          traditional: true,
          success: function (data, status) {

            //success
          },
          error: function (xhr, ajaxOptions, thrownError) {
            $.mobile.loading('hide');
          }

        });

    }; //Save

控制器方法如下所示:

public Function SaveOrder(vm As OrdersModels.EditViewModel) As JsonResult

  Dim o As Sales.Order = GetCurrentOrder(vm.OrderId)

  With o
    .FirstCrop = vm.FirstCropId
    .SecondCrop = vm.SecondCropId
    .PreviousCrop = vm.PreviousFirstCropId

    'code to save order
 End function

OrdersModels.EditViewModel 如下所示:

Public Class EditViewModel
   Public Property OrderId As Guid
   Public Property FirstCropId As Integer
   Public Property SecondCropId As Integer

   Public Property ProductDataList As List(Of OrderProducts)
End Class

Public Class OrderProducts
  Public Property Id As Integer
  Public Property Rate As Decimal
  Public Property Variable As Decimal
End Class

控制器正在获取除 vm.ProductDataList 之外的所有数据。我尝试了各种方法,例如将 JSON.stringify(viewModel.currentOrder) 作为数据传递,添加 contentType: 'application/json; charset=utf-8' 没有运气。

如何将数据传递给控制器​​?

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    这应该可以工作

    $.ajax({
           type: 'POST',
           url: url,
           contentType:'application/json; charset=utf-8',
           dataType: 'json',
           data:ko.toJSON(self.currentOrder),
           success: function (data, status) {
                       //success
           },
           error: function (xhr, ajaxOptions, thrownError) {
              $.mobile.loading('hide');
           }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 2014-04-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多