回发 Razor 页面时读取数据表行

Read Datatable Rows when postback Razor Pages

如图所示,我使用表单字段中的添加行按钮填充数据 table,一旦我添加了所有需要的行(订单创建)创建按钮将被点击,我想把客户端创建的数据 table 的数据发送到服务器端,这样我就可以将它们保存在数据库中,怎么办?

My Create Form

服务器端代码如下

public class CreateModel : PageModel
    {
        private readonly ArabianCement.Models.ArabianCementContext _context;
        private readonly IConfiguration _configuration;

        public CreateModel(ArabianCement.Models.ArabianCementContext context, IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }
        [BindProperty]
        public Guid VendorGUIDBind { get; set; }


        [BindProperty]
        public List<tbl_AC_Trans_Detail> gridBind { get; set; } = new List<tbl_AC_Trans_Detail>();

        public IActionResult OnGet()
        {
        ViewData["AC_Trans_GUID"] = new SelectList(_context.tbl_AC_Trans, "AC_Trans_GUID", "AC_Trans_GUID");
        ViewData["Cement_GUID"] = new SelectList(_context.LK_Cements, "Cement_GUID", "Cement_Name");
        ViewData["Vendor_GUID"] = new SelectList(_context.LK_Sources, "Source_GUID", "Source_Name");

            return Page();
        }

        [BindProperty]
        public tbl_AC_Trans_Detail tbl_AC_Trans_Detail { get; set; }

        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }



            tbl_AC_Tran objMainTrans = new tbl_AC_Tran();
            Guid sellGUID = Guid.Parse(_configuration["AppKeys:SellGUID"]);
            objMainTrans.AC_Trans_GUID = Guid.NewGuid();
            objMainTrans.Creation_Date = DateTime.Now;
            objMainTrans.Vendor_GUID = VendorGUIDBind;
            objMainTrans.Trans_Type = sellGUID;

            //_context.tbl_AC_Trans.Add(objMainTrans);
            //await _context.SaveChangesAsync();


            //_context.tbl_AC_Trans_Details.Add(tbl_AC_Trans_Detail);
           // await _context.SaveChangesAsync();

            //return RedirectToPage("./Index");
            return RedirectToPage();
        }

        public IEnumerable<LK_Cement_Type> GetModels(Guid cementGUID)
        {
            IEnumerable<LK_Cement_Type> model = _context.LK_Cement_Types.Where(x => x.Cement_GUID == cementGUID).ToList();
            return model;
        }

        public JsonResult OnGetCementTypes(string id)
        {
            Guid guid = Guid.Parse(id);
            return new JsonResult(GetModels(guid));
        }
    }

cshtml 代码如下

@using Newtonsoft.Json;
@using System.Web;

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

<h1>Create</h1>

<h4>tbl_AC_Trans_Detail</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @*<div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="form-control" />
                <span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
            </div>*@

            <div class="form-group">
                <label class="control-label">Vendor</label>
                <select asp-for="VendorGUIDBind" class ="form-control" asp-items="ViewBag.Vendor_GUID" id="ddlVendor">
                </select>
            </div>

            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.Cement_GUID" class ="form-control" asp-items="ViewBag.Cement_GUID" id="ddlCement">
                    <option value="">Select Cement</option>
                </select>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class ="form-control" asp-items="ViewBag.Cement_Type_GUID" id="ddlCementType">
                    <option value="">Select Cement Type</option>
                </select>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="control-label">Cement Quantity</label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="form-control" id="txtCementQuantity"/>
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Price" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Price" class="form-control" id="txtCementPrice" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Total_Amount" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.Total_Amount" class="form-control" id="txtTotalAmount" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" class="text-danger"></span>
            </div>
            <div class="form-group">
                @*<input type="submit" value="Create" class="btn btn-primary" asp-action="OnPostAsync" />*@

                <input type="submit" value="Create" class="btn btn-primary" onclick="testFun()" />
                <input type="button" value="addRow" class="btn btn-primary" onclick="AddProduct()" />
            </div>

        </form>
    </div>
</div>

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Vendor GUID</th>
            <th>Vendor Name</th>
            <th>Cement Guid</th>
            <th>Cement Name</th>
            <th>Cement Type Guid</th>
            <th>Cement Type Name</th>
            <th>Quantity </th>
            <th>Cement Price</th>
            <th>Total</th>
        </tr>
    </thead>
 
    <tfoot>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tfoot>
</table>




<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    <script type="text/javascript">
        $(function () {
            $("#ddlCement").on("change", function() {
                var cement = $(this).val();
                $("#ddlCementType").empty();
                $("#ddlCementType").append("<option value=''>Select Type</option>");
                $.getJSON("?handler=CementTypes",{ id: cement}, (data) => {
                    $.each(data, function (i, item) {
                        $("#ddlCementType").append('<option value='+item.cement_Type_GUID+'>'+item.cement_Type_Name+'</option>');
                    });
                });
            });
        });

        $("#txtCementQuantity,#txtCementPrice").focusout(function () {
           //alert('ddlCurrency');

           var cementQuantity = document.getElementById("txtCementQuantity").value;
           var cementPrice = document.getElementById("txtCementPrice").value;
           var totalAmount=0;

           document.getElementById("txtTotalAmount").value = cementQuantity * cementPrice;


           });

           function AddProduct() {

        var t = $('#example').DataTable();
    var counter = 1;
    t.row.add( [
            $("#ddlVendor Option:Selected").val(),
            $("#ddlVendor Option:Selected").text(),
            $("#ddlCement Option:Selected").val(),
            $("#ddlCement Option:Selected").text(),
            $("#ddlCementType Option:Selected").val(),
            $("#ddlCementType Option:Selected").text(),
            document.getElementById("txtCementQuantity").value,
            document.getElementById("txtCementPrice").value,
            document.getElementById("txtTotalAmount").value
        ] ).draw();
 
        counter++;
    }

    function testFun()
    {
        //var json = JsonConvert.SerializeObject(Html(#e), Formatting.Indented);
        alert('Test');
    }








$(document).ready(function () {
    $("#example2").DataTable({
    "paging": true,
    responsive: true,
    "searching": true,
    "ordering": true,
     dom: 'Bfrtip',
            buttons: [
                 'excel'
            ],
    "order": [[1, "asc"]]
    });
    });
    </script>
}

点击AddRow button.Also时,您可以尝试将行数据放入表格的隐藏div中,您需要删除onclick="testFun()"。这是一个将行数据传递给[的演示=13=]:

cshtml:

@using Newtonsoft.Json;
@using System.Web;

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

<h1>Create</h1>

<h4>tbl_AC_Trans_Detail</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @*<div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="form-control" />
                <span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
            </div>*@

            <div class="form-group">
                <label class="control-label">Vendor</label>
                <select asp-for="VendorGUIDBind" class ="form-control" asp-items="ViewBag.Vendor_GUID" id="ddlVendor">
                </select>
            </div>

            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.Cement_GUID" class ="form-control" asp-items="ViewBag.Cement_GUID" id="ddlCement">
                    <option value="">Select Cement</option>
                </select>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class="control-label"></label>
                <select asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class ="form-control" asp-items="ViewBag.Cement_Type_GUID" id="ddlCementType">
                    <option value="">Select Cement Type</option>
                </select>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="control-label">Cement Quantity</label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="form-control" id="txtCementQuantity"/>
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Cement_Price" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Price" class="form-control" id="txtCementPrice" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="tbl_AC_Trans_Detail.Total_Amount" class="control-label"></label>
                <input asp-for="tbl_AC_Trans_Detail.Total_Amount" class="form-control" id="txtTotalAmount" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" class="text-danger"></span>
            </div>
            <div id="hiddenData" style="display: none;">
            
            </div>
            <div class="form-group">
                @*<input type="submit" value="Create" class="btn btn-primary" asp-action="OnPostAsync" />*@

                <input type="submit" value="Create" class="btn btn-primary"/>
                <input type="button" value="addRow" class="btn btn-primary" onclick="AddProduct()" />
            </div>

        </form>
    </div>
</div>

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Vendor GUID</th>
            <th>Vendor Name</th>
            <th>Cement Guid</th>
            <th>Cement Name</th>
            <th>Cement Type Guid</th>
            <th>Cement Type Name</th>
            <th>Quantity </th>
            <th>Cement Price</th>
            <th>Total</th>
        </tr>
    </thead>
 
    <tfoot>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tfoot>
</table>




<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    <script type="text/javascript">
        var index = 0;
        $(function () {
            $("#ddlCement").on("change", function() {
                var cement = $(this).val();
                $("#ddlCementType").empty();
                $("#ddlCementType").append("<option value=''>Select Type</option>");
                $.getJSON("?handler=CementTypes",{ id: cement}, (data) => {
                    $.each(data, function (i, item) {
                        $("#ddlCementType").append('<option value='+item.cement_Type_GUID+'>'+item.cement_Type_Name+'</option>');
                    });
                });
            });
        });

        $("#txtCementQuantity,#txtCementPrice").focusout(function () {
           //alert('ddlCurrency');

           var cementQuantity = document.getElementById("txtCementQuantity").value;
           var cementPrice = document.getElementById("txtCementPrice").value;
           var totalAmount=0;

           document.getElementById("txtTotalAmount").value = cementQuantity * cementPrice;


           });

           function AddProduct() {

        var t = $('#example').DataTable();
    var counter = 1;
    t.row.add( [
            $("#ddlVendor Option:Selected").val(),
            $("#ddlVendor Option:Selected").text(),
            $("#ddlCement Option:Selected").val(),
            $("#ddlCement Option:Selected").text(),
            $("#ddlCementType Option:Selected").val(),
            $("#ddlCementType Option:Selected").text(),
            document.getElementById("txtCementQuantity").value,
            document.getElementById("txtCementPrice").value,
            document.getElementById("txtTotalAmount").value
        ] ).draw();
        const div = document.createElement('div');

        div.className = 'row';

        div.innerHTML = '<input type="text" name="AddedRows[' + index + '].Vendor_GUID" value="' + $("#ddlVendor Option:Selected").val() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Vendor_Name" value="' + $("#ddlVendor Option:Selected").text() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_GUID" value="' + $("#ddlCement Option:Selected").val() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_Name" value="' + $("#ddlCement Option:Selected").text() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_Type_GUID" value="' + $("#ddlCementType Option:Selected").val() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_Type_Name" value="' + $("#ddlCementType Option:Selected").text() + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_Quantity" value="' + document.getElementById("txtCementQuantity").value + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Cement_Price" value="' + document.getElementById("txtCementPrice").value + '" />' +
            '<input type="text" name="AddedRows[' + index + '].Total_Amount" value="' + document.getElementById("txtTotalAmount").value + '" />' ;
        document.getElementById('hiddenData').appendChild(div);
        index++;
        counter++;
    }

    function testFun()
    {
        //var json = JsonConvert.SerializeObject(Html(#e), Formatting.Indented);
        alert('Test');
    }








$(document).ready(function () {
    $("#example2").DataTable({
    "paging": true,
    responsive: true,
    "searching": true,
    "ordering": true,
     dom: 'Bfrtip',
            buttons: [
                 'excel'
            ],
    "order": [[1, "asc"]]
    });
    });
    </script>
}

cshtml.cs:

public class CreateModel : PageModel
    {
        private readonly ArabianCement.Models.ArabianCementContext _context;
        private readonly IConfiguration _configuration;

        public CreateModel(ArabianCement.Models.ArabianCementContext context, IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }
        [BindProperty]
        public Guid VendorGUIDBind { get; set; }


        [BindProperty]
        public List<tbl_AC_Trans_Detail> gridBind { get; set; } = new List<tbl_AC_Trans_Detail>();
        [BindProperty]
        public List<TestModel> AddedRows { get; set; }
        public IActionResult OnGet()
        {
        ViewData["AC_Trans_GUID"] = new SelectList(_context.tbl_AC_Trans, "AC_Trans_GUID", "AC_Trans_GUID");
        ViewData["Cement_GUID"] = new SelectList(_context.LK_Cements, "Cement_GUID", "Cement_Name");
        ViewData["Vendor_GUID"] = new SelectList(_context.LK_Sources, "Source_GUID", "Source_Name");

            return Page();
        }

        [BindProperty]
        public tbl_AC_Trans_Detail tbl_AC_Trans_Detail { get; set; }

        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }



            tbl_AC_Tran objMainTrans = new tbl_AC_Tran();
            Guid sellGUID = Guid.Parse(_configuration["AppKeys:SellGUID"]);
            objMainTrans.AC_Trans_GUID = Guid.NewGuid();
            objMainTrans.Creation_Date = DateTime.Now;
            objMainTrans.Vendor_GUID = VendorGUIDBind;
            objMainTrans.Trans_Type = sellGUID;

            //_context.tbl_AC_Trans.Add(objMainTrans);
            //await _context.SaveChangesAsync();


            //_context.tbl_AC_Trans_Details.Add(tbl_AC_Trans_Detail);
           // await _context.SaveChangesAsync();

            //return RedirectToPage("./Index");
            return RedirectToPage();
        }

        public IEnumerable<LK_Cement_Type> GetModels(Guid cementGUID)
        {
            IEnumerable<LK_Cement_Type> model = _context.LK_Cement_Types.Where(x => x.Cement_GUID == cementGUID).ToList();
            return model;
        }

        public JsonResult OnGetCementTypes(string id)
        {
            Guid guid = Guid.Parse(id);
            return new JsonResult(GetModels(guid));
        }
    }
public class TestModel {
        public Guid Vendor_GUID { get; set; }
        public string Vendor_Name { get; set; }
        public Guid Cement_GUID { get; set; }
        public string Cement_Name { get; set; }

        public Guid Cement_Type_GUID { get; set; }
        public string Cement_Type_Name { get; set; }
        public int Cement_Quantity { get; set; }
        public int Cement_Price { get; set; }
        public int Total_Amount { get; set; }

    }