[英]How to pass the list of objects from view to MVC controller using json.stringify
I have tried with following code but shows null in the controller side.. 我尝试使用以下代码,但在控制器端显示为null。
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: Emp.cs:
public class Emp
{
public int empid { get; set; }
public string name{get;set;}
}
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!! 在Google进行了大量搜索之后。我找到了将对象列表发布到控制器的方法。我在代码中做了一些修改……在这里!
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:
使用JavaScriptSerializer,您可以将字符串数据转换为类列表对象。如果您在下面看到我的代码,则可以更好地理解它:
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. 为了使用JavaScriptSerializer类,在控制器中包括此(System.Web.Script.Serialization)名称空间。
Hope this helps !! 希望这可以帮助 !! Happy coding :)
快乐的编码:)
There is problem with data that you are sending to server. 您发送到服务器的数据有问题。 you don't need to JSON.stringify 2 times.
您不需要JSON.stringify 2次。
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
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.