【问题标题】:ASP.NET MVC Ajax: Passing an IList from the View to the ControllerASP.NET MVC Ajax:将 IList 从视图传递到控制器
【发布时间】:2010-05-17 10:20:53
【问题描述】:

我需要使用 POST 将网格行从视图传递到控制器。这个想法是传递具有以下结构的对象(人)的 IList:

  • 字符串名称
  • 字符串地址
  • 字符串 ID

我想从 JQGrid 中读取数据并将其传递给控制器​​以填充 IList。

我正在尝试构建数据对象以传递 Ajax 数据参数。

这里是 Javascript 代码:

$("#saveButton").click(
 function()
 {
   var returnData = '{';
   var existingIDs = $('#listPeople').getDataIDs();

   if (idsPeople.length > 0)
   {
     for (i=0;i<idsPeople.length;i++) 
     {

//Trying to build the obejct data

ret = ret + '"people['+ i +'].Name":' $('#listPeople').getRowData(idsPeople[i]).Name + ',';

ret = ret + '"people['+ i +'].Address":' $('#listPeople').getRowData(idsPeople[i]).Address+ ',';

ret = ret + '"people['+ i +'].Id":' $('#listPeople').getRowData(idsPeople[i]).Id+ ',';

//If it has more than one element
      if (idsPeople.length>1 && (i+1)<idsPeople.length)
      {
        ret = ret + ',';
      }
    }
  }

ret = ret + '}';

我的 Ajax 发送函数:

var url_all = '<%=Url.Action("SaveData") %>;

$.ajax({
type: "POST",
url: url_all,
data: ret,
dataType: "json",
success: function(){
   alert("OK");
 },
error: function(){
   alert("Error: check SaveData");
 } 
});

我的控制器:

public ActionResult SaveData(IList<PeopleHeader> people){

   // using debug to know if "people" variable has any values

   return Json(true);
}

我遇到的问题是一个错误:“System.NotSupportedException: Fixed size collection”,并且没有数据被传递。

我认为我的问题取决于创建对象...有没有更简单的方法来执行此过程?

提前致谢,

【问题讨论】:

    标签: .net asp.net-mvc ajax


    【解决方案1】:

    问题是您将 JSON 编码数据发布到 action 方法,但 action 方法只接受表单编码数据(又名 contentType:application/www-x-form-urlencoded)。

    我认为如果您只是删除该行:

    数据类型:“json”

    它应该工作。或者,如果你真的想发布 JSON,你可以试试 JsonValueProvider。

    http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      相关资源
      最近更新 更多