如何使用json.stringify将对象列表从视图传递到MVC控制器 [英] How to pass the list of objects from view to MVC controller using json.stringify

查看:157
本文介绍了如何使用json.stringify将对象列表从视图传递到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码但在控制器端显示为null ..

I have tried with following code but shows null in the controller side..

查看:

<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" />

控制器:

public void getemplist(List<Emp> emp) 
{ }

Emp.cs:

public class Emp
{
public int empid { get; set; }
public string name{get;set;}
} 


推荐答案

经过google的大量搜索后,我找到了将对象列表发布到控制器的方法..我在代码中修改了一点......这里是!!

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!!

脚本:

var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
    emp = JSON.stringify(emp)
    $.post("/Home/getemplist/", { 'emp': emp }) 

控制器:

这里我只是将参数更改为字符串类型。使用JavaScriptSerializer,您可以将此字符串数据转换为您的类列表对象..如果您看到我的代码,您可以更好地理解它:

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

    }

在控制器中包含此(System.Web.Script.Serialization)命名空间,以便使用JavaScriptSerializer类。

Include this (System.Web.Script.Serialization) namespace in your controller inorder to use the JavaScriptSerializer class.

希望这有帮助!!快乐的编码:)

Hope this helps !! Happy coding :)

这篇关于如何使用json.stringify将对象列表从视图传递到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆