【问题标题】:Send data from dynamically created fields to controller将数据从动态创建的字段发送到控制器
【发布时间】:2020-10-04 16:29:29
【问题描述】:

我目前正在处理一个 .NET Core 项目,并且我有一个包含不同字段的表单。有些是可以通过使用 jQuery/Javascript 按下按钮来动态生成的字段

$(function() {

  $(".addRow").click(function(e) {
    e.preventDefault();
    var template = $("#items").find(".itemRow").first();
    var newRow = template.clone();
    newRow.find("input.formfield").val("");
    $("#items").append(newRow);

  });

  // I have tried adding this set of Javascript code to pass data to the `Controller` when I press the button Submit, but it doesn't work..

  $("#btnSubmit").click(function(e) {
    e.preventDefault();
    var _this = $(this);
    var url = _this.closest("form").attr("action");

    var rows = [];
    var items = $(".itemRow");

    $.each(items, function(i, item) {
      var tbOne = $(item).find("input[name='tbOne']").val();
      var tbTwo = $(item).find("input[name='tbTwo']").val();

      var row = {
        Test1: tbOne,
        Test2: tbTwo
      };
      rows.push(row);
    });

    //Let's post to server
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(rows),
        contentType: "application/json"
      })
      .done(function(result) {
        //do something with the result
      })

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" asp-controller="Test" asp-action="Insert">
<div class="form-group row">
    <div class="col-lg-1">
        <label>Name</label>
    </div>
    <div class="col-lg-3">
        <input type="text" asp-for="name" name="Name" />
    </div>
    <div class="col-lg-1">
        <label>Age</label>
    </div>
    <div class="col-lg-3">
        <input type="text" asp-for="age" name="Age" />
    </div>
</div>

<div id="items">
    <div class="itemRow">
        <div class="form-group row">
            <div class="col-lg-1">
                <label>Tb One</label>
            </div>
            <div class="col-lg-3">
                <input type="text" asp-for="tbOne" name="tbOne" />
            </div>
            <div class="col-lg-1">
                <label>Tb Two</label>
            </div>
            <div class="col-lg-3">
                <input type="text" asp-for="tbTwo" name="tbTwo" />
            </div>
            <div class="col-lg-2">
                <button type="button" class="addRow">Add Row</button>
            </div>
        </div>
    </div>
</div>
</form>

控制器:

public IActionResult Insert(IEnumerable<Model> model)
{
      foreach (var item in model)
      {
          // to do here
      }
}

我希望有人可以为我提供建议,告诉我如何进一步改进此代码以成功从动态生成的字段中获取数据。

【问题讨论】:

  • 您没有任何 ID addrow。您拥有的按钮位于 itemrow 内,因此如果您使用需要唯一的 ID,它将停止工作
  • @mplungjan 嗨,我为粗心的错误道歉。我已经更新了我的代码。
  • 看我的回答。你需要$("#items").on("click",".addRow", function(e) {

标签: json asp.net-mvc .net-core controller


【解决方案1】:
  1. 为 addrow 按钮使用一个类并将其委托或移动到 itemRow 之外
  2. 不要对数据进行字符串化,ajax 会为你做这件事

$(function() {

  $("#items").on("click",".addRow", function(e) {
    e.preventDefault();
    var template = $("#items").find(".itemRow").first();
    var newRow = template.clone();
    newRow.find("input.formfield").val("");
    $("#items").append(newRow);

  });

  // I have tried adding this set of Javascript code to pass data to the `Controller` when I press the button Submit, but it doesn't work..

  $("#btnSubmit").click(function(e) {
    e.preventDefault();
    var _this = $(this);
    var url = _this.closest("form").attr("action");

    var rows = [];
    var items = $(".itemRow");

    $.each(items, function(i, item) {
      var tbOne = $(item).find("input[name='tbOne']").val();
      var tbTwo = $(item).find("input[name='tbTwo']").val();

      var row = {
        Test1: tbOne,
        Test2: tbTwo
      };
      rows.push(row);
    });

    //Let's post to server
    $.ajax({
        type: "POST",
        url: url,
        data: rows,
        contentType: "application/json"
      })
      .done(function(result) {
        //do something with the result
      })

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" asp-controller="Test" asp-action="Insert">
  <div id="items">
    <div class="itemRow">
      <div class="form-group row">
        <div class="col-lg-3">
          <input type="text" asp-for="name" name="Name" />
        </div>
        <div class="col-lg-3">
          <input type="text" asp-for="age" name="Age" />
        </div>
      </div>

      <div class="form-group row">
        <div class="col-lg-3">
          <input type="text" asp-for="tbOne" name="tbOne" />
        </div>
        <div class="col-lg-3">
          <input type="text" asp-for="tbTwo" name="tbTwo" />
        </div>
        <div class="col-lg-2">
          <button class="addRow" type="button">Add Row</button>
        </div>
      </div>
    </div>
  </div>
</form>

【讨论】:

  • 我关心的不是动态生成字段。我无法将生成字段的值传递给我的控制器...
  • 好的,那将是另一个问题。现在你至少有不止一排。如果[ { "Test1": "tbOne", "Test2": "tbTwo" },{ "Test1": "tbOne", "Test2": "tbTwo" }] 的 JSON 字符串会被public IActionResult Insert(IEnumberable&lt;Model&gt; model){ foreach (var item in model){ ... } } 读取,也许会问一个 ASP 问题
  • 在新帖子中?还是在当前问题中?
  • 新帖子。它可以简化为仅显示您发送的实际 JSON 的示例以及如何解析它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 2015-10-16
相关资源
最近更新 更多