如何通过AjaxForm从一个表单提交按钮将输入传递给一个到多个表

时间:2017-10-24 20:56:50

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

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

这是我桌子的edmx图:

enter image description here

我的模特:

 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表而没有任何问题。

因为无论我做什么,它都会以无效方式返回服务。当我调试它时,我将得到第一个表的输入,但没有任何东西会传递给第二个查询,即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();


            }

谢谢!

1 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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");
});
&#13;
<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>
&#13;
&#13;
&#13;

编辑:包含对删除的重新索引。