In my page I have some inputs for users to input values, then I shall get all the values and send them to server. Now I can get the value and I display them just like below:
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
But i dont know how to send them to action for saving. I'm using mvc.
In the view I write the following 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++;
}
});
Can anyone help me?
-
I take it you're using jQuery. Are you wanting to see how to use AJAX to send a JavaScript array to the server? I can't see any MVC - is this the generic design pattern, or do you mean the .net technology?halfer– halfer2012年12月24日 10:03:13 +00:00Commented Dec 24, 2012 at 10:03
-
Thanks guys all above. You are so kind.牛さん– 牛さん2012年12月24日 13:54:11 +00:00Commented Dec 24, 2012 at 13:54
2 Answers 2
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...
}
});
Comments
I used the following tutorial, which I found in this SO question to write this answer. While this code hasn't been tested, hopefully it should put you on track. Please don't hesitate to ask if you have further questions.
After having populated your orderModel
array in javascript, all you've left is posting that data with jquery. The jquery object contains an ajax
method (documentation) which let you do that conveniently. The code below, placed at the end of your javascript code should do the trick:
$.ajax({
type: 'POST',
traditional: true,
data: { models: orderModel }
});
Note that this ajax call will be performed on the URL of the displayed page. To choose a different URL, use the following code:
$.ajax(URL, { /* same data as above */ });
On the server side, as per the tutorial, you should have a class definition which holds a models
property. That property will be filled in with the javascript array data you have collected in your script.
Merry Christmas!