2012-12-24 113 views
3

在我的页面中,我有一些输入用于用户输入值,然后我将获取所有值并将它们发送到服务器。现在,我可以得到价值,我展示他们就像如下:将JS数组传递给MVC控制器动作

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

谁能帮助我?

+0

我认为你使用的是jQuery。您是否想要了解如何使用AJAX将JavaScript数组发送到服务器?我看不到任何MVC - 这是通用设计模式,还是您的意思是.net技术? – halfer

+0

感谢上面的人。你真好。 – Wayou

回答

3
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... 
     } 
    }); 
+0

谢谢让我们知道。 – didierc

2

我用下面的tutorial,我在这SO question找到这个答案。尽管此代码尚未经过测试,但希望它能让您走上正轨。请不要犹豫,问你是否还有其他问题。

在javascript中填充了orderModel数组后,您所剩下的就是使用jquery发布数据。 jquery对象包含一个ajax方法(documentation),可让您方便地执行此操作。下面的代码,放置在你的JavaScript代码到底是应该做的伎俩:

$.ajax({ 
    type: 'POST', 
    traditional: true, 
    data: { models: orderModel } 
}); 

注意,这个Ajax调用将在显示的页面的URL来进行。要选择不同的URL,使用下面的代码:

$.ajax(URL, { /* same data as above */ }); 

在服务器端,按照本教程中,你应该有一个类定义其持有models属性。该属性将填充您在脚本中收集到的javascript数组数据。

圣诞快乐!

+0

谢谢你的anwser。 – Wayou

+0

你是否设法让它工作? – didierc

+0

不,我用其他方式来完成这个。 – Wayou

相关问题