如何对象的列表从视图中透过JSON.stringify传递到MVC控制器[解决] [英] How to pass the list of objects from view to MVC controller using json.stringify [solved]

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

问题描述

我曾尝试与以下code,但显示了控制器侧空..

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;}
} 

请帮我解决这个..

推荐答案

很多谷歌搜索后..我发现张贴的对象列表到控制器..我已经修改了一点在我的$ C $方式ç...这里是!

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可以能够将此字符串数据转换到您的类对象列表..你可以更好地理解它,如果你看到我下面的code:

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天全站免登陆