【问题标题】:How to pass inputs to one to many table from one form submit button via AjaxForm如何通过 AjaxForm 从一个表单提交按钮将输入传递给一对多表
【发布时间】:2018-04-05 19:16:31
【问题描述】:

我目前正在尝试通过 HTML 表单插入模型对象,但是在调试时,它是作为空对象的第二个表,即使我指定的输入字段的名称属性与模型中调用它们的方式相匹配。

这是我的表的 edmx 图:

我的模特:

 public class TReportHeaderModel
    {

        public int ID { get; set; }
        public int ClientID { get; set; }
        public string  THeaderTitle { get; set; }
        public int RowNumber { get; set; }

        public IList<TReporURLModel> TotalReports { get; set; }


    }


 public class TReporURLModel
    {
        public int ID { get; set; }
        public string  name { get; set; }
        public string url { get; set; }
        public int RowNumber { get; set; }
        public string hash { get; set; }
        //public int THeaderID { get; set; }
    }

这是我作为模态的 HTML 表单。请忽略 JavaScript,因为它是一种演示我在这里尝试实现的表单功能的方式。

但是,我提交表单的ajax如下:

 initCreateGroupForm: function ()
    {
        $('#create-report-group-form').ajaxForm({

            dataType: 'json',
            beforeSerializate: function ($form, options) {

                Reporting.Forms = $form;
            },
            success: function (response) {

                if (response.Success == true) {
                    JQueryUX.Msg.BootStrapShow({
                        msg: response.Message,
                        className: 'alert alert-success',
                        title: 'Report Has Been Created.'
                    });

                    $("#create-report-group-modal").modal('hide');


                }
                else {
                    alert(response.Message);
                }



            },
            onError: function (xhr, status, error)
            {
                alert(error);

            }

        });

$(document).ready(function() {
  $("#add_row").on("click", function() {
    // Dynamic Rows Code

    // Get max row id and set new id
    var newid = 0;
    $.each($("#tab_logic tr"), function() {
      if (parseInt($(this).data("id")) > newid) {
        newid = parseInt($(this).data("id"));
      }
    });
    newid++;

    var tr = $("<tr></tr>", {
      id: "addr" + newid,
      "data-id": newid
    });

    // loop through each td and create new elements with name of newid
    $.each($("#tab_logic tbody tr:nth(0) td"), function() {
      var cur_td = $(this);

      var children = cur_td.children();

      // add new td and element if it has a nane
      if ($(this).data("name") != undefined) {
        var td = $("<td></td>", {
          "data-name": $(cur_td).data("name")
        });

        var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
        c.attr("name", $(cur_td).data("name") + newid);
        c.appendTo($(td));
        td.appendTo($(tr));
      } else {
        var td = $("<td></td>", {
          'text': $('#tab_logic tr').length
        }).appendTo($(tr));
      }
    });

    // add delete button and td
    /*
    $("<td></td>").append(
        $("<button class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>")
            .click(function() {
                $(this).closest("tr").remove();
            })
    ).appendTo($(tr));
    */

    // add the new row
    $(tr).appendTo($('#tab_logic'));

    $(tr).find("td button.row-remove").on("click", function() {
      $(this).closest("tr").remove();
    });
  }); <!--Ends Here-->








  $("#add_row").trigger("click");
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" id="create-report-group-form" action="@Url.Action(" CreateReport ", "TReporting ")" method="post">
  <input type="hidden" id="hidden-report-group-id" name="ID" value="null" />
  <div class="col-lg-12 table-responsive">
    <div class="col-lg-12" style="margin-bottom:20px;margin-left:-18px;">
      <label> Report Group Title</label>
      <input type="text" class="form-control" id="input-report-header-title" placeholder="Report Group Title" name="THeaderTitle">
    </div>
    <table class="table table-bordered table-hover table-sortable" id="tab_logic">
      <thead>
        <tr>
          <th class="text-center">
            Report Name
          </th>
          <th class="text-center">
            URLs
          </th>
          <th>
            <button id="add_row" type="button" class="btn btn-success" data-role="add">
                                            <span class="glyphicon glyphicon-plus"></span>
                                        </button>
          </th>
        </tr>
      </thead>


      <tbody>
        <tr id='addr0' data-id="0" class="">

          <td data-name="name">
            <input type="hidden" id="hidden-report-url-id" name="ID" value="null" />
            <input type="text" id="input-report-name" name='name' placeholder='Report Name' class="form-control" />
          </td>
          <td data-name="url">
            <input type="text" id="input-report-url" name='url' placeholder='https://' class="form-control" />
          </td>


          <td data-name="del">
            <button name="del0" type="button" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>
          </td>
        </tr>

      </tbody>


    </table>
    <div class="modal-footer">
      <button type="submit" class="btn-save btn btn-primary btn-block">Save</button>
      <button type="button" class="btn-cancel btn btn-secondary btn-block">Cancel</button>

    </div>
    <!--Modal-Footer Ends Here-->
  </div>
  <!---Model Body Ends Here-->

</form>

是否有特定的方法来调用属于第二个表的输入,以便输入可以毫无问题地传递到 TReport 表。

因为无论我做什么,它都会以 null 的形式返回到服务中。当我调试它时,我将获得第一个表的输入,但没有任何内容会传递给第二个查询,即 TReport 表。我的服务代码如下:

 public void CreateReport(TReportHeaderModel model)
        {

            using (var connection = new TReportEntitiesConnection())

            {
                connection.THeader.Add(new THeader()
                {
                    ID = model.ID,
                    THeaderTitle = model.THeaderTitle,
                    RowNumber = model.RowNumber


                });

                foreach (var urls in model.TotalReports)
                {

                    connection.TReport.Add(new TReport()
                    {
                        TReportName=urls.name,
                        URL=urls.url


                    });


                }

                connection.SaveChanges();


            }

谢谢!

【问题讨论】:

  • 您没有创建具有正确 name 属性的输入,尽管您认为它们需要是 name="TotalReports[0].ID"name="TotalReports[1].ID" 等(请参阅 this answer 以获得解释
  • 您似乎想要动态创建(和删除)新的收藏项,在这种情况下,请参阅this answer
  • @StephenMuecke 嗨斯蒂芬,当我尝试使用 for 循环进行循环时,它仍然给我空结果。你能告诉我一些正确处理这种方法的例子吗?
  • 看看我给你的两个链接,特别是第二个,因为你似乎想要动态添加收藏项
  • @GerleBatde 仅供参考,我在回答中包含了重新索引,请告诉我它对您的工作原理。

标签: jquery asp.net-mvc linq-to-sql linq-to-entities ajaxform


【解决方案1】:

我清理了你的一些 HTML 并重写了一些 JavaScript。此代码未经测试,因此请告诉我它是如何为您工作的。

var index = 0;
var rowTemplate =
  `<tr id='addrINDEX' data-id="INDEX" class="">
    <td data-name="name">
      <input type="text" id="input-report-name" name='TotalReports[INDEX].name' placeholder='Report Name' class="form-control" />
    </td>
      <td data-name="url">
        <input type="text" id="input-report-url" name='TotalReports[INDEX].url' placeholder='https://' class="form-control" />
      </td>
      <td data-name="del">
        <button type="button" class='btn btn-danger glyphicon glyphicon-remove row-remove' onClick="deleteRow(INDEX);"></button>
      </td>
    </tr>`;

function realignIndexes() {
  var newIndex = 0;
  $.each($("#tab_logic tbody tr"), function() {
  
    // update table row id
    var tr = $(this);
    tr.attr("id", "addr" + newIndex);
    tr.attr("data-id", newIndex);

    // update inputs name
    var inputs = $(this).find(":input");
    inputs.each(function(index) {
      var e = $(this);
      var id = $(this).attr("id");
      if (id == "input-report-name") {
        $(this).attr('name', "TotalReports[" + newIndex + "].name");
      } else if (id == "input-report-url") {
        $(this).attr('name', "TotalReports[" + newIndex + "].url");
      }
    });
    
    // update button param
    var btn = $(this).find(":button");
    btn.attr("onclick", "deleteRow(" + newIndex + ")");

    newIndex++;
  });
}

function addRow() {
  var newTemplate = rowTemplate.replace(/INDEX/g, index);

  // add the new row
  $(newTemplate).appendTo($('#tab_logic'));
  index++;
};

function deleteRow(i) {
  if (index > 1) {
    $("#addr" + i).remove();
    index--;
    realignIndexes();
  }
};

$("#add_row").on("click", function() {
  addRow();
});

$(document).ready(function() {
  $("#add_row").trigger("click");
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="create-report-group-form" action="@Url.Action(" CreateReport ", "TReporting ")" method="post">
  <div class="panel">
    <div class="panel-body">
      <div class="h5">
        <label>Report Group Title</label>
        <input type="text" class="form-control" id="input-report-header-title" placeholder="Report Group Title" name="THeaderTitle">
      </div>
      <div class="table-responsive">
        <table class="table table-bordered table-hover table-sortable" id="tab_logic">
          <thead>
            <tr>
              <th class="text-center">Report Name</th>
              <th class="text-center">URLs</th>
              <th><button id="add_row" type="button" class="btn btn-success" data-role="add"><span class="glyphicon glyphicon-plus"></span></button></th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit" class="btn-save btn btn-primary btn-block">Save</button>
      <button type="button" class="btn-cancel btn btn-secondary btn-block">Cancel</button>
    </div>
  </div>
</form>

编辑:包括删除时的重新索引。

【讨论】:

  • 我现在来测试一下。非常感谢!
  • 没问题,随时。如果您遇到任何问题,请发表评论,我也许可以提供帮助。
  • 嗨,大卫,我想出了一种方法来追加新索引#。但是,如果已经有预先添加的索引怎么办。那么从那里,如何找出索引以添加更多行?
  • jsfiddle.net/Gereltuya/oyjnw1ok。这是示例。我的 Ajax 正在为 tbody 附加索引号,但是当我尝试添加更多项目时。它从索引 0 开始。如何获取每个表的最大索引?
  • @GerleBatde 一个表应该只有一个 tbody。我会删除您在 html 中的一些额外内容。当我这样做时,您的小提琴正在正确索引。我确实注意到您输入的 data-name 和 name 属性是附加数字而不是覆盖,当您发布到服务器时这很可能会导致问题。
猜你喜欢
  • 1970-01-01
  • 2019-02-10
  • 2012-09-11
  • 2016-10-28
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
相关资源
最近更新 更多