How to pass the list of objects from view to MVC controller using json.stringify
11,076
Solution 1
After a lot of searches in google.. I found the way to post the list of objects to controller.. i have modified little bit in my code... here it is!!
script :
var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
emp = JSON.stringify(emp)
$.post("/Home/getemplist/", { 'emp': emp })
Controller:
Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:
public void getemplist(string emp)
{
List<Emp> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData = jss.Deserialize<List<Emp>>(emp);
// DO YOUR OPERATION ON LIST OBJECT
}
Include this (System.Web.Script.Serialization) namespace in your controller inorder to use the JavaScriptSerializer class.
Hope this helps !! Happy coding :)
Solution 2
There is problem with data that you are sending to server. you don't need to JSON.stringify 2 times.
function getme() {
debugger;
var emp = [
{ empid: 1, name: 'sasi' },
{ empid: 2, name: 'sathish' }
];
emp = JSON.stringify({ emp: emp });//make json string once
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/getemplist',
data: emp //send it to server
});
}
Author by
sasi
Updated on June 14, 2022Comments
-
sasi almost 2 years
I have tried with following code but shows null in the controller side..
view:
<script> function getme(){ debugger; var emp = [ { empid: 1, name: 'sasi' }, { empid: 2, name: 'sathish'} ]; emp = JSON.stringify({ 'emp': emp }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Home/getemplist', data: JSON.stringify(emp) }); } </script> <input type="button" onclick="getme();" value="Click me" />
controller:
public void getemplist(List<Emp> emp) { }
Emp.cs:
public class Emp { public int empid { get; set; } public string name{get;set;} }