![](/img/trans.png)
[英]Passing knockout.js observablearray object to MVC Controller Action?
[英]Passing JS array to MVC controller action
在我的頁面中,我有一些輸入供用戶輸入值,然后我將獲取所有值並將它們發送到服務器。 現在我可以得到值,我就像下面一樣顯示它們:
Cylinder: 0.00 Sphere: 0.00 Quantity:1
Cylinder: -0.25 Sphere: 0.00 Quantity:2
Cylinder: -0.50 Sphere: 0.00 Quantity:33
Cylinder: -0.75 Sphere: 0.00 Quantity:2
Cylinder: -1.00 Sphere: 0.00 Quantity:2
Cylinder: -1.25 Sphere: 0.00 Quantity:33
Cylinder: -1.50 Sphere: 0.00 Quantity:4
Cylinder: -1.75 Sphere: 0.00 Quantity:5
Cylinder: -2.00 Sphere: 0.00 Quantity:4
但我不知道如何將它們發送到保存行動。 我正在使用mvc。
在視圖中,我編寫了以下JavaScript:
var orderModel={};
$(".bulkOrderNumericInput").each(function (index,element) {
if ($(this).val().length!=0) {
orderModel[i]={Cylinder:$(this).attr('valuex'),Sphere:$(this).attr('valuey'),Quantity:$(this).val()};
i++;
}
});
誰能幫我?
var orderModel = [];
//loop all the inputs in the page to get values, let's say you give all the inputs a class named'.orderinput'
$('#checkout').click(function(){
$(".orderinput").each(function(){
orderModel.push({Cylinder:$(this).val(),Sphere:blah,Quantity:blah,...);
});
});
//not all values are sotred into the orderModel, the do the post
$.ajax({
url: 'your url',
data:JSON.stringify(orderModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',//this is important!!
success : function(msg) {
//blah..
},
error: function (xhr, ajaxOptions, thrownError) {
//blah...
}
});
我使用了以下教程 ,我在這個問題中找到了這個答案。 雖然這段代碼還沒有經過測試,但希望它能讓你走上正軌。 如果您有其他問題,請隨時詢問。
在javascript中填充orderModel
數組之后,您剩下的就是使用jquery發布該數據。 jquery對象包含一個ajax
方法( 文檔 ),可以方便地執行此操作。 放在javascript代碼末尾的下面代碼應該可以解決問題:
$.ajax({
type: 'POST',
traditional: true,
data: { models: orderModel }
});
請注意,此ajax調用將在顯示頁面的URL上執行。 要選擇其他URL,請使用以下代碼:
$.ajax(URL, { /* same data as above */ });
在服務器端,根據教程,您應該有一個包含models
屬性的類定義。 該屬性將使用您在腳本中收集的javascript數組數據填充。
聖誕節快樂!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.