以ASP.NET MVC表形式动态添加行

时间:2019-05-11 04:38:36

标签: c# jquery html asp.net asp.net-mvc

我正在尝试在ASP.NET MVC表下方编写一个“添加”按钮,以动态附加空白行,然后单击“提交”按钮以将每一行保存到数据库中。

SO上有several similar questions,但我没有一个可以应用于此。我一直在尝试应用this example,但“添加”按钮未附加新行。

型号:

public class TableForm
    {
        public int Id { get; set; }
        public List<TableFormData> TableFormDatas { get; set; }
    }

    public class TableFormData
    {
        public int Id { get; set; }
        public string ClientSampleID { get; set; }
        public string AdditionalComments { get; set; }
        public string AcidStables { get; set; }

剃刀视图:

@model NewTestSix.Models.TableForm

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

<fieldset>
    <legend>Sample submission</legend>
    <table id="submissionTable" class="table table-bordered">
        <thead>
            <tr>
                <td>Sample ID</td>
                <td>Additional Comments</td>
                <td>Acid-stable amino acids</td>
            </tr>
        </thead>

        <tr id="tablerow0">
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
                </div>
            </td>
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
                </div>
            </td>
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
                </div>
            </td>
            <td>
                <button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
            </td>
            <td>

            </td>
        </tr>

    </table>
    <p>
        <button id="add" type="submit" class="btn btn-primary">Add</button>
    </p>
    <hr />

    <p>
        <input type="submit" value="Create" class="btn btn-default" />
    </p>
</fieldset>
}

@section Scripts {
    <script src="~/bundles/jqueryval.js" type="text/javascript">
        var counter = 1;
        $(function () {

            $('#add').click(function () {
                $('<tr id="tablerow' + counter + '"><td>' +
                    '<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                    '</td>' +
                    '</tr>').appendTo('#submissionTable');
                counter++;
                return false;
            });
        });
        function removeTr(index) {
            if (counter > 1) {
                $('#tablerow' + index).remove();
                counter--;
            }
            return false;
        }
    </script>

在此阶段,我对与控制器的模型绑定并不太烦恼,我只想让此添加按钮起作用。控制器示例:

  [HttpPost]
        public ActionResult Index(string any = "")
        {
            IList<TableForm> _TableForm = new List<TableForm>();

            //Loop through the forms
            for (int i = 0; i <= Request.Form.Count; i++)
            {
                var ClientSampleID = Request.Form["ClientSampleID[" + i + "]"];
                var additionalComments = Request.Form["AdditionalComments[" + i + "]"];
                var acidStables = Request.Form["AcidStables[" + i + "]"];

                if (!String.IsNullOrEmpty(ClientSampleID))
                {
                    _TableForm.Add(new TableForm { ClientSampleID = ClientSampleID, AcidStables = acidStables, AdditionalComments = additionalComments });
                }
            }

            return View();
        }

感谢您的见解。

当前: current

点击“添加”按钮后需要: enter image description here

2 个答案:

答案 0 :(得分:3)

更改您的

<button id="add" type="submit" class="btn btn-primary">Add</button>

进入

<button id="add" class="btn btn-primary">Add</button>

我不认为Add按钮应该做submit

然后从您的src="~/bundles/jqueryval.js"标记中删除script部分。根据此answer,我们不应在此处保留src属性。

<script type="text/javascript">
    var counter = 1;
    //... the rest of your code is here...
</script>

如果您实际上有一个jqueryval.js文件,请将其放在另一个<script>标签中。

如果我没记错的话,这就是您所期望的结果。

var counter = 1;
        $(function () {
            $('#add').click(function () {
                $('<tr id="tablerow' + counter + '"><td>' +
                    '<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                    '</td>' +
                    '</tr>').appendTo('#submissionTable');
                counter++;
                return false;
            });
        });
        function removeTr(index) {
            if (counter > 1) {
                $('#tablerow' + index).remove();
                counter--;
            }
            return false;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
        <legend>Sample submission</legend>
        <table id="submissionTable" class="table table-bordered">
            <thead>
                <tr>
                    <td>Sample ID</td>
                    <td>Additional Comments</td>
                    <td>Acid-stable amino acids</td>
                </tr>
            </thead>

            <tr id="tablerow0">
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
                    </div>
                </td>
                <td>
                    <button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
                </td>
                <td></td>
            </tr>

        </table>
        <p>
            <button id="add" type="button" class="btn btn-primary">Add</button>
        </p>
        <hr />

        <p>
            <input type="submit" value="Create" class="btn btn-default" />
        </p>
    </fieldset>

让我知道是否有帮助。

答案 1 :(得分:1)

您可以使用jQuery jqGrid

  

这是免费且开源的jquery插件。这是完全   已启用Ajax以显示表格数据并进行操作。另外,   我们可以应用不同的Jquery UI主题,请参见演示。

操作方法:这里没有任何内容,因为我们将使用json格式的Ajax获取产品详细信息。

    public ActionResult GetProducts(string sidx, string sord, int page, int rows)
{
  var products = Product.GetSampleProducts();
  int pageIndex = Convert.ToInt32(page) - 1;
  int pageSize = rows;
  int totalRecords = products.Count();
  int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

  var data = products.OrderBy(x => x.Id)
                .Skip(pageSize * (page - 1))
                .Take(pageSize).ToList();

  var jsonData = new
  {
      total = totalPages,
      page = page,
      records = totalRecords,
      rows = data
  };

  return Json(jsonData, JsonRequestBehavior.AllowGet);
}

并将此标签添加到目标页面

<table id="jqGrid"></table>
<div id="jqGridPager"></div>

在脚本部分之后,添加以下内容:

<script>
var myGrid = $('#jqGrid');
myGrid.jqGrid({
      url: '/Home/GetProducts/',
      datatype: "json",
      contentType: "application/json; charset-utf-8",
      mtype: 'GET',
      colNames: ['ProductID', 'Name', 'Price', 'Department', 'Action'],
      colModel: [
          { name: 'Id', key: true, width: 75 },
          { name: 'Name', key: true, width: 200 },
          { name: 'Price', key: true, width: 75 },
          { name: 'Department', key: true, width: 200 },
          { name: 'Edit', key: true, width: 100, editable: true, formatter: editButton }
      ],
      rowNum: 4,
      pager: '#jqGridPager',
      gridview: true,
      rownumbers: true,
      pagerpos: 'center'
});
</script>

原始帖子为here