I have a viewModel like the following:
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>
I am trying to pass viewModel.currentOrder to the MVC controller like as follows:
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
The controller method looks like this:
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 looks like this:
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
The controller is getting all data except vm.ProductDataList is nothing. I tried all sorts of things like passing JSON.stringify(viewModel.currentOrder) as data, adding contentType: 'application/json; charset=utf-8' without luck.
How to pass the data to the controller?
This should work
$.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');
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments