2013-04-29 129 views
1

我想将对象传递给控制器​​并检索控制器中的值。 我定义了诸如:如何使用ajax调用将对象传递给控制器​​

HTML代码:

var positionarray = []; 

的Javascript:

$("#button").live('click',function(){ 
    positionarray.push({ 
     id: sessionStorage.getItem('id'), 
     value: $("#input").val() 
    }); 
}); 

// on save button click 
$.ajax({ 
     type: "GET",             
     url:"/Bugs/Position",             
     data: { 
      array:positionarray  
     }, 
     cache: false, 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     success: function (json) { 

     } 
}); 

但我不能够在控制器中检索值。它变为空。

+0

你的动作是怎样的? – PSL 2013-04-29 04:58:12

+0

在'/ Bugs/Position'页打印你的'Request',并检查你得到了什么,我认为它是正确的。 – 2013-04-29 04:59:47

+0

我能够传递给控制器​​,但在控制器中获得的值为空 – Jonathan 2013-04-29 05:01:25

回答

3

试试这个: - 你传入对象的数组,所以你应该做的HTTPPost而非HTTPGET(这会为基本类型的数组工作说INT的名单,strgin等)通过查询字符串发送它(记住查询字符串限制)。 用HTTPPost试试这个

$.ajax({ 
     type: "POST",      
     url:"Home/Position",             
     data: JSON.stringify({ 
       array: positionarray 
     }), 
     cache: false, 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     success: function (json) { 

     } 

[HTTPPost] 
public void Position(YourClass[] array){... 
0

尝试了这一点:

$.ajax({ 
     type: "GET",             
     url:"/Bugs/Position",             
     data: 'array='+positionarray  
     cache: false, 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     success: function (json) { 

     } 
}); 
+0

有什么区别? – Jonathan 2013-04-29 05:02:04

+0

将它作为字符串而不是对象传递。我有一种感觉,就是因为你的数组是JSON类型的,它正在恶化数据对象。 – Mysteryos 2013-04-29 05:02:58

0

试试这个:

ajax call必须在按钮的点击函数,那么它会工作,

在你的代码,你的前点击你的ajax call运行,从而它将通过null 到您的控制器

$("#button").live('click',function(){ 
    positionarray.push({ 
     id: sessionStorage.getItem('id'), 
     value: $("#input").val() 
    }); 


    // on save button click 
    // this code must run after `button click` and after pushing data in 
    // positionarray variable 
    $.ajax({ 
      type: "GET",             
      url:"/Bugs/Position",             
      data: { 
       array:positionarray  
      }, 
      cache: false, 
      dataType: "json", 
      contentType: "application/json; charset=utf-8", 
      success: function (json) { 

      } 
    });// here ajax function code ends 

});// here button click function ends 
+0

Yah当然这就是我正在做的 – Jonathan 2013-04-29 05:20:17

+0

@Naidu检查一次,在你的''问题''你的''ajax代码'是'按钮点击功能'外。 – 2013-04-29 05:21:34

+0

但是我写了一个评论,说ajax会在按钮中点击 – Jonathan 2013-04-29 05:52:18

相关问题