【问题标题】:ASP MVC, Ajax: return array of array of integers to controller methodASP MVC,Ajax:将整数数组返回给控制器方法
【发布时间】:2018-06-14 04:40:33
【问题描述】:

我遇到了这个问题,我尝试通过 AJAX 调用将用户在网页上输入的数据发布到控制器方法。数据永远不会到达控制器,它总是会抛出错误。问题可能是控制器期望的数据与 AJAX 调用发送给它的数据类型不同,但我真的不知道预期数据应该是什么样子。

这是构建数组的 JS/jQuery,它是一个表格单元格值数组的数组:

    var i = 0;
    var cells = new Array(); // cell values in one column
    var rows = new Array(); // list of columns (rows)

    $('#datatable').find('tr').each(function () {
        $('td :not([type="button"],[id="Nr."])', this).each(function () {
            cells.push($(this).val());
        });
        if (i > 0) {
            rows.push(cells);
            cells = [];
        }
        i++;
    });

这就是 AJAX 调用的样子:

    rows = JSON.stringify({ 'rows': rows });

    $.ajax({
        url: "/Home/Q_FourthPage",
        type: "POST",
        datatype: "json",
        traditional: true,
        data: rows,
        success: function (response) {
            alert("Success");
            console.log("Sucess ", response);
        },
        error: function (response) {
            alert("Error");
            console.log("Error ", response);
        }
    });

控制器仍然是空的 - 它应该获取什么参数才能使数据作为字符串/整数/其他数组的数组到达?谢谢。

编辑:这是 Q_FourthPage 控制器方法使用的视图模型:

public class Q4_Answer_VM
{
    public Models.User User { get; set; }
    public List<Models.Capacity> Matrix { get; set; } //this is where the data should go
                                                      //a capacity describes one row of the table
    public Models.QuestionText TMatrix { get; set; }

}

容量类如下所示 - 它是表格的一行。

public class Capacity
{
    // This class is a model for the capacity matrix. it represents one column.

    //PK        
    public int ID { get; set; }

    //FK
    public int Questionnaire_ID { get; set; }

    //Values
    public String Load { get; set; }
    public String Source { get; set; }
    public String Goal { get; set; }
    public String Frequency { get; set; }
    public String Distance { get; set; }


    public virtual Questionnaire Questionnaire_ { get; set; }


}

这是控制器方法的头部:

  [HttpPost]
  public ActionResult Q_FourthPage(ViewModels.Q4_Answer_VM vm)

这些类中有很多属性——这就是调用失败的原因吗?

编辑 2:视图

这是视图:

@model MyANTon.ViewModels.Q4_Answer_VM

@{
    ViewBag.Title = "myANTon Anforderungserfassung";
    ViewBag.HideNavBar = false;
}

@using (Html.BeginForm(Html.BeginForm("Q_FourthPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })))

{

    <div class="container">
        <div align="center">
            <ol class="breadcrumb" align="center" text-align="center">
                <li class="breadcrumb-item">@Html.ActionLink("Lasten", "Q_Firstpage", "Home", new { @class = "elements" }, null)</li>
                <li class="breadcrumb-item">@Html.ActionLink("Lastaufnahme-/abgabe", "Q_Secondpage", "Home", new { @class = "elements" }, null)</li>
                <li class="breadcrumb-item">@Html.ActionLink("Weitere Anforderungen", "Q_Thirdpage", "Home", new { @class = "elements" }, null)</li>
                <li class="breadcrumb-item"><b><u>@Html.ActionLink("Kapazitäten", "Q_Fourthpage", "Home", new { @class = "elements" }, null)</u></b></li>
                <li class="breadcrumb-item">@Html.ActionLink("Auftragserzeugung", "Q_Fifthpage", "Home", new { @class = "elements" }, null)</li>
            </ol>
        </div>
        <div class="jumbotron">

            <div>
                @Html.TextBox("file", "", new { type = "file" }) <br />

                <input type="submit" value="Upload" />

                @ViewBag.Message

            </div>

            <h1>4. Kapazitätsbetrachtung</h1>
            <p>Wie viele Fahrzeuge werden benötigt? Um dies auszurechnen wird eine Transportmatrix benötigt.</p>
            <p>Ein Beispiel einer Transportmatrix ist in Tabelle 1 zu sehen.</p>
            <p>Um die Anzahl der Roboter zu berechnen ist auch eine Angabe der Produktionsschichten relevant:</p>
            <ul>
                <li>In wie vielen Schichten läuft die Fertigung?</li>
            </ul>
            <p>
                Um mögliche Engpässe oder Umwege zu betrachten ist ein Layout der Produktionsstätte wie in Abbildung 3 von Vorteil.
                Idealerweise mit Angaben über andere Verkehrsteilnehmer (Personenverkehr, Staplerverkehr, Kreuzungen).
            </p>
            <input type="button" id="BtnPlus" name="BtnPlus" class="BtnPlus" value="Zeile hinzufügen (+)" align="center" style="vertical-align: middle" />

            <table class="grid" id="datatable" style="table-layout:fixed">
                <thead>
                    <tr style="text-align: center" id="header">
                        <th style="vertical-align: middle" id="Nr.">Nr.</th>
                        <th>Last</th>
                        <th>Quelle</th>
                        <th>Ziel</th>
                        <th>Frequenz [/h]</th>
                        <th>Abstand [m]</th>
                        <th>Zeile löschen</th>
                </thead>
                <tbody></tbody>
            </table>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-default" name="Speichern" value="Speichern" id="BtnSave" />
                    <input type="submit" class="btn btn-default" name="Speichern und weiter" value="Speichern und weiter" />
                    <input type="button" class="btn btn-default" value="Weiter zu Schritt 5" onclick="@("window.location.href='" + @Url.Action("Q_Fifthpage", "Home") + "'");" />
                </div>

            </div>

        </div>
    </div>

}


<script src="~/Scripts/jquery-3.2.1.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
@Scripts.Render("~/bundles/datatables")

编辑编号。 3:由于下面用户 derloopkat 提供的解决方案,它现在可以工作了。作为提示:Ajax 和 Forms 似乎不能很好地结合在一起。我不得不将“保存”按钮移到表单之外(@using...{})。

【问题讨论】:

  • 你会分享 Q_FourthPage 动作和模型类吗?
  • 查看我的编辑,我添加了视图模型、“容量”的模型类,它是数组的数组和控制器方法的开始。我知道我没有传递班级期望的所有数据。我想先只发送数组数据,然后在控制器中构建容量矩阵,然后再将其保存到数据库中。
  • 显然您正在发送一个字符串矩阵(数组数组)并且您的网络方法应该收到“[HttpPost] public ActionResult Q_FourthPage(string[] rows)'
  • 我想我正在发送一个字符串数组。但是,string[] rows 只是一个字符串数组?
  • 即使它是一个列表而不是矩阵,您的 html 页面对于每个单元格也只有一个值,而在 List&lt;Models.Capacity&gt; 中,Capacity 有不同的成员。价值去哪儿了?

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


【解决方案1】:

这行得通。事情是在 json 中创建一个与模型中的确切名称和结构匹配的对象。您不需要将所有成员都包含在您的 json 中,但如果您希望能够在服务器上检索他们的值,那么出现的成员应该与模型匹配。

var capacities = new Array(); // cell values in one column
$('#datatable').find('tr').each(function () {
    var cells = $(this).find('td :not([type="button"],[id="Nr."])');
    var capacity = {
        Load: cells[0].value,
        Source: cells[1].value,
        Goal: cells[2].value,
        Frequency: cells[3].value,
        Distance: cells[4].value
    };
    capacities.push(capacity);
});

在您的 Ajax 调用中,dataType 是您希望从服务器获取的内容,而不是您发送的类型(即 contentType)。

var model = JSON.stringify({ 'Matrix': capacities });
$.ajax({
    url: "/Home/Q_FourthPage",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    traditional: true,
    data: model,
    success: function (response) {
        alert("Success");
        console.log("Sucess ", response);
    },
    error: function (response) {
        alert("Error");
        console.log("Error ", response);
    }
});

我的桌子是虚拟的 Html。

<table id="datatable">
    <tr>
        <td><input type="text" value="11" /></td>
        <td><input type="text" value="12" /></td>
        <td><input type="text" value="13" /></td>
        <td><input type="text" value="14" /></td>
        <td><input type="text" value="15" /></td>
    </tr>
    <tr>
        <td><input type="text" value="21" /></td>
        <td><input type="text" value="22" /></td>
        <td><input type="text" value="23" /></td>
        <td><input type="text" value="24" /></td>
        <td><input type="text" value="25" /></td>
    </tr>
</table>

而动作方法是:

[HttpPost]
public ActionResult Q_FourthPage(ViewModels.Q4_Answer_VM vm)
{
    return View("Index");
}

如果您打算从这里返回 json,那么您需要在 Ajax 调用中添加dataType: 'json'

【讨论】:

  • 感谢您的回答。不幸的是,这在这里不起作用。控制器中的 vm 仍然为空,我仍然收到来自 ajax 调用的错误消息。此外,jquery 函数不会从表中获取所有数据,而是仅获取第一行 n 次,n 是表中td 的数量。有没有办法可以查看 ajax 数据的内容,例如在调试器中或类似的东西中?
  • 复制行问题是由您的第二个each 引起的,它没有使用父“每个”的当前行。需要添加$(this).find 来解决这个问题。我已经编辑了我的答案。关于 vm 模型收到 null 和错误消息,请检查您的代码有什么不同。
  • 非常感谢,我会在星期一试试这个并回复你!
  • 视图中的某些模型绑定是否可能是问题所在?目前,我的观点相当复杂,因为有很多人在研究它。我会用视图更新问题。
  • @mneumann,如果Capacity有一个带参数的构造函数并且没有无参数构造函数,那会在你的代码运行之前破坏活页夹。但这有理由猜测。您需要能够根据stackoverflow.com/help/mcve规则在发布问题之前重现您遇到的错误。
猜你喜欢
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2016-01-06
  • 2013-12-15
  • 1970-01-01
相关资源
最近更新 更多