Reputation: 1669
I want to pass an object to controller and retrieve the values in the controller. I have defined like:
Html code:
var positionarray = [];
Javascript:
$("#button").live('click',function(){
positionarray.push({
id: sessionStorage.getItem('id'),
value: $("#input").val()
});
});
// on save button click
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: {
array:positionarray
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});
But i am not able to retrieve the values in the controller. It is getting null.
Upvotes: 3
Views: 29500
Reputation: 708
My Example :
// Class
namespace Bookstore.ViewModels {
public class ShoppingViewModel {
public int id { get; set; }
public int quentity { get; set; }
}
}
/// Shopping Cart
$(function () {
$(".Quantity").on("click", function () {
debugger
var model = {};
model.id = parseInt($(this).val());
model.quentity = parseInt($(this).next().val());
$.ajax({
type: "POST",
url: "/Cart/ModifiedCart",
data:model,
success: function (result) {
console.log(result);
}
});
});
});
[HttpPost]
public JsonResult ModifiedCart(ShoppingViewModel model)
{
return Json(model);
}
Upvotes: 0
Reputation: 123739
Try this:- You are passing an array of objects so you should do HTTPPost rather than HttpGet (this will work for array of primitive types say list of int, strgin etc) sending it through query string(Remember the limit for query string). Try this with HTTPPost
$.ajax({
type: "POST",
url:"Home/Position",
data: JSON.stringify({
array: positionarray
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
[HTTPPost]
public void Position(YourClass[] array){...
Upvotes: 5
Reputation: 40639
Try this:
Your ajax call
must be in button click function then it will work,
In your code your ajax call
runs before your click so it will pass null
to your controller
$("#button").live('click',function(){
positionarray.push({
id: sessionStorage.getItem('id'),
value: $("#input").val()
});
// on save button click
// this code must run after `button click` and after pushing data in
// positionarray variable
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: {
array:positionarray
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});// here ajax function code ends
});// here button click function ends
Upvotes: 0
Reputation: 5791
Try this out:
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: 'array='+positionarray
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});
Upvotes: 0