【问题标题】:Use a call Ajax to send an Array of string to mvc Controller使用调用 Ajax 将字符串数组发送到 mvc 控制器
【发布时间】:2015-09-01 00:44:48
【问题描述】:

我正在尝试从表列中获取值,我将其放入数组中,然后将其发送到我的控制器。发生了一些非常奇怪的事情,你会在下面看到:

这是我的 JS 代码:

var result = [];

        $('td:nth-child(' + columnNbr + ')').each(function () {
            var t = $(this).html();
            result.push(t);
        });

        $.ajax({
            type: "POST",
            url: '@Url.Action("UpdateTable", "Home")',
            dataType: "html",
            traditional: true,
            data: { values: result },
            success: function (data) {
            }
        });

我的数组“结果”很好地填充了我需要的值。

这是我的控制器:

public ActionResult UpdateTable(List<string> values)
{
    return View("index");
}

这会返回 500 内部错误。 让我发疯的是 -> 如果我将我的 JS 从我发布的内容修改为:

        //$('td:nth-child(' + columnNbr + ')').each(function () {
        //    var t = $(this).html();
        //    result.push(t);
        //});

        result.push("test1");
        result.push("test2");

Ajax 调用工作正常...我检查了“typeof $.(this).html()”,都是字符串!

我不知道出了什么问题。

【问题讨论】:

  • console.log 您的结果数组,可能是已发布数组的大小。能否提供一些测试表数据?
  • 这是我的数组:["2015-06-16", "0", "0", "206000", "206000", "100", "0", "30558", “14,83”、“14,83”、“9”、“19”、“147”、“0”、“0”、“88,04”、“0”、“0”、“0”、 “0”、“0”、“0”、“0”、“0”、“0”、“87917”、“-174422”、“2849”、“0”、“0”、“62,1” , " "]
  • 数组中的最后一项是问题("&lt;input type="button" value="Edit" id="4"&gt; ")。排除它
  • 你可以试试{ values: result },而不是JSON.stringify({ values: result }),它对我有用。

标签: javascript jquery arrays ajax asp.net-mvc


【解决方案1】:

为什么不直接使用 $.post()

var result = [];

$('td:nth-child('+columnNbr+')').each(function(){
    result.push($(this).text());
});

$.post('@Url.Action("UpdateTable", "Home")', {values: result});

或者如果您需要回调:

$.post('@Url.Action("UpdateTable", "Home")', {values: result}, function(data){
    // what to do
});

【讨论】:

    【解决方案2】:

    您只需将var t = $(this).html(); 更改为var t = $(this).text();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多