【问题标题】:How to pass the list of objects from view to MVC controller using json.stringify如何使用 json.stringify 将对象列表从视图传递到 MVC 控制器
【发布时间】:2014-06-21 02:39:19
【问题描述】:

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

查看:

<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# javascript jquery asp.net-mvc


    【解决方案1】:

    在谷歌进行大量搜索后..我找到了将对象列表发布到控制器的方法..我在我的代码中修改了一点......就在这里!

    脚本:

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

    控制器:

    这里我只是将参数更改为字符串类型。使用 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
    
        }
    

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

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

    【讨论】:

      【解决方案2】:

      您发送到服务器的数据有问题。你不需要 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
          });
       }
      

      【讨论】:

      • 事实上,您永远不需要 JSON.stringify。 jQuery 将负责对对象本身进行字符串化。另外,JSON.stringify 与某些版本的 IE 不兼容。 jQuery 确保一切都保持兼容(如果您使用 1.x 版本)。
      • 如果没有 JSON.stringify,它似乎无法工作。是的,它与某些版本的 IE 不兼容,所以在这种情况下,我们可以使用 polyfill。
      • 感谢您的回复,伙计们。最后它对我有用。在控制器操作中,我刚刚将参数类型更改为字符串,例如:public void getemplist(string emp)。然后使用 javascript 序列化程序类,我能够将字符串数据转换为列表对象。在脚本中,我刚刚改变了方式我将控制器操作称为 $.post("/Home/getemplist/", { 'emp': emp })。我稍后会在这里发布我的整个代码.. :) :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多