Reputation: 463
I am trying to generate a list with AJAX and post it to controller. Here is my code so far;
var objects = new Array();
here is a loop {
var object = {
a: 1,
b: 2,
c: 3
};
objects[i] = object;
i++;
}
$.ajax({
type: "POST",
url: "/Controller/Poster",
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(objects),
success: function (result) {
alert("posted");
}
});
Am I following the right way till here?
And in back end I created a model class;
public class ObjectModel
{
public int a {get; set;}
public int b {get; set;}
public int c {get; set;}
}
Now I am trying to get this object list to my controller. After a research I tried create a controller method that takes an object list as parameter;
[HttpPost]
public JsonResult Poster(List<ObJectModel> olist)
{
}
But I can't define a list in my controller. What am I supposed to do from now? And should I make any changes in my code?
Thanks!
Upvotes: 1
Views: 1676
Reputation: 463
I added System.Collections namepace to my controller. And I can define List now. After I added [HttpPost] attribute to my method and make public my class properties now there isn't any problem. My main problem was the System.Collections namespace. I successfully passed my object list to my controller.
Upvotes: 2
Reputation: 3215
try
data: $.param(objects),
insted of
data: JSON.stringify(objects),
Upvotes: 0
Reputation: 3933
Try this
data: objects
instead of
data: JSON.stringify(objects)
Add attribute to Poster
[HttpPost]
public JsonResult Poster(List<ObJectModel> olist)
Change ObjectModel
public class ObjectModel
{
public int a {get; set;}
public int b {get; set;}
public int c {get; set;}
}
Upvotes: 0