【问题标题】:Post list using jquery ajax使用 jquery ajax 发布列表
【发布时间】:2017-04-05 12:59:57
【问题描述】:

我在 razor 中有这段代码

@{
    var aid = new List<int>();
    foreach (var item in Model.applications)
    {
        if (item.Status == 1)
        {
            aid.Add(item.Id);
        }
    }
}

在 js 中我有这个:

<script>
function checkIfSigned() {

    var data = { aid: @aid };
    console.log(data);

    $.ajax({
        url: '@Url.Action("Method", "Controller")',
        type: "POST",
        data: data,
        ...
    });
}

在我的控制器中:

public JsonResult Method(List<int> aid)
{
  foreach (var item in aid)
  { ... }
}

我的问题是:

var 数据 = { 援助:@aid };

抛出异常:

未捕获的语法错误:未终止的模板文字

var data = { 辅助:System.Collections.Generic.List`1[System.Int32] };

我能做什么?如何发布列表?

【问题讨论】:

  • 对象的字符串表示就是该对象的类名。您也许可以在将对象输出到页面时对其进行 JSON 序列化。虽然你为什么首先需要这样做?您将未修改的数据发送回刚刚为您提供该数据的服务器。似乎没有必要。
  • 您需要将您的 c# 列表转换为 javascript 数组。但是为什么你的视图中的代码(它属于你的控制器)
  • 我知道它应该在控制器中,但现在我没有任何其他方法。我必须使用超时检查这些值
  • 抱歉,您的所作所为毫无意义(正如@David 所指出的,它毫无意义)- 但您可以使用 var data = { aid: @Html.Raw(Json.Encode(aid)) }; 并且您需要 data: JSON.stringify(data);contentType: 'application/json',
  • @StephenMuecke 谢谢。我应该在action方法中传递什么类型的参数?

标签: c# jquery ajax asp.net-mvc razor


【解决方案1】:

你可以这样做:

var data = []; // javascript array
@foreach(var item in Model.applications)
{
    if (item.Status == 1)
    {
        <text> 
           /* start JS */
           data.push('@item.Id'); 
           /* end JS */
        </text>
    }
}

在 JS Ajax 中:

    <script>
    function checkIfSigned() {

        console.log(data);

        $.ajax({
            url: '@Url.Action("Method", "Controller")',
            type: "POST",
            data: data,
            ...
        });
    }
    </script>

【讨论】:

  • 只需删除这一行:var data = {aid:@aid};
  • 我有 (IEnumerable&lt;string&gt; data) 作为参数,但调用没有进入它并记录内部 500 错误
  • 好吧,这是因为内容类型。我删除它并调用进入方法但IEnumerable&lt;int&gt; dataIEnumerable&lt;string&gt; data 都是空的..
  • 试试这个:$.ajax({ url: '@Url.Action("Method", "Controller")', type: "POST", data: {aid: data}, ... });
  • 我也在尝试
猜你喜欢
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2021-01-17
  • 2016-12-14
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多