【问题标题】:passing array from javascript to controller MVC 4将数组从javascript传递到控制器MVC 4
【发布时间】:2013-08-07 19:53:20
【问题描述】:

我正在使用剃须刀,我很难将数组传递给控制器​​。该数组包含我制作的对象,我正在尝试这样做:

$.ajax({
     type: "POST",
     url: "HomePage/HandleOperations",
     data: JSON.stringify(operationCollection),
     success: function (data) { alert("SUCESS");},
     dataType: "json",
     contentType: "application/json"
});

我的控制器是:

 public void HandleOperations(List<string> operationCollection)
 {

 }

我不需要使用 ajax,但我不知道还能怎么做。在控制器中,它显示“operationCollection”包含元素,但它们都是空的。

【问题讨论】:

  • 旁注 - 你不需要调用 JSON.stringify,jQuery(或 XHR2)会为你做这件事。
  • 您是否尝试将 traditional: true 添加到您的 ajax 选项中?
  • 还是同样的问题,它显示了正确数量的元素,但它们都是空的
  • 你试过用 string[] 代替吗?

标签: javascript ajax asp.net-mvc-4 razor


【解决方案1】:

Ajax 参数

traditional : true

会成功的。

【讨论】:

  • 什么意思?我应该在哪里写繁体??
  • $.ajax({ type: "POST", url: "HomePage/HandleOperations", data: {operations: operationCollection}, 传统: true, success: function (data) { alert("SUCCESS "); } });
【解决方案2】:

客户端:

$.ajax({
     type: "POST",
     url: "HomePage/HandleOperations",
     data: {operations: operationCollection},
     success: function (data) { alert("SUCCESS"); }
});

并像这样声明一个类服务器端:

public class Operation
{
  public int Index;
  public string Source;
  public string Target;
  public int AddOrDel;
}

那么你可以有这个动作:

public void HandleOperations(Operation[] operations)
{
}

【讨论】:

  • 这行得通!我不知道我需要一个模型。谢谢
  • 嗯,需要和需要,你将有机会在物品上写字,毕竟它们是操作:)
  • 在 json 版本中,您保留对 JSON.Stringify 和 dataType: "json" 的调用,并有一个将字符串作为参数的操作,public void HandleOperations(string operations),然后调用var operationArr = JavaScriptSerializer.Deserialize(operations);,你需要在你的项目中添加对 System.Web.Extensions 的引用
  • 您实际上不需要模型,使用传统:true 将在 ajax 帖子中完成。
【解决方案3】:

ajax 调用的传统:true 参数的用法:

为了帮助 radbyx,使用 ajax 调用的“traditional:true”属性,如下所示,将告诉 ajax 使用传统形式的序列化。更多详情:http://api.jquery.com/jQuery.param/What is "traditional style of param serialization' in JQuery

$.ajax({
     type: "POST",
     url: "HomePage/HandleOperations",
     data: {operations: operationCollection},
     traditional: true,
     success: function (data) { alert("SUCCESS"); }
});

【讨论】:

    【解决方案4】:

    在您的 ajax 中添加“traditional:true”参数。

    示例:

    var parentValueToPush=new Array();
    $('[name=SelectedUsers]:checked').each(function () {
                parentValueToPush.push($(this).val());
                temp.push($(this).val());
            });
            $.ajax({
                url: //URL,
                type: 'get',
                traditional: true,
                dataType: 'html',
                cache: false,
                data: { SelectedUsers: parentValueToPush},
                success: function (data) {
                       //Result
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2013-08-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多