Home > Enterprise >  Read Datatable Rows when postback Razor Pages
Read Datatable Rows when postback Razor Pages

Time:02-01

As shown in the Image, I fill the data table with the add row button from the fields in the form, once I add all the needed rows (Order Creation) Create button will be clicked, I want to send the data of the data table that was created on the client-side to the server-side so I can save them in the database, how to do this?

My Create Form

Server-side code below

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 code below

@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 >
    <div >
        <form method="post">
            <div asp-validation-summary="ModelOnly" ></div>
            @*<div >
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" ></label>
                <input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID"  />
                <span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" ></label>
                <select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
            </div>*@

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

            <div >
                <label asp-for="tbl_AC_Trans_Detail.Cement_GUID" ></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 >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" ></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 >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" >Cement Quantity</label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Quantity"  id="txtCementQuantity"/>
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Price" ></label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Price"  id="txtCementPrice" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.Total_Amount" ></label>
                <input asp-for="tbl_AC_Trans_Detail.Total_Amount"  id="txtTotalAmount" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" ></span>
            </div>
            <div >
                @*<input type="submit" value="Create"  asp-action="OnPostAsync" />*@

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

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

<table id="example"  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>
}

CodePudding user response:

You can try to put rowdata into hidden div of the form when click AddRow button.Also,you need to remove onclick="testFun()".Here is a demo to pass rows data to List<TestModel> AddedRows:

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 >
    <div >
        <form method="post">
            <div asp-validation-summary="ModelOnly" ></div>
            @*<div >
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" ></label>
                <input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID"  />
                <span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" ></label>
                <select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
            </div>*@

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

            <div >
                <label asp-for="tbl_AC_Trans_Detail.Cement_GUID" ></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 >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" ></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 >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" >Cement Quantity</label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Quantity"  id="txtCementQuantity"/>
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.Cement_Price" ></label>
                <input asp-for="tbl_AC_Trans_Detail.Cement_Price"  id="txtCementPrice" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" ></span>
            </div>
            <div >
                <label asp-for="tbl_AC_Trans_Detail.Total_Amount" ></label>
                <input asp-for="tbl_AC_Trans_Detail.Total_Amount"  id="txtTotalAmount" />
                <span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" ></span>
            </div>
            <div id="hiddenData" style="display: none;">
            
            </div>
            <div >
                @*<input type="submit" value="Create"  asp-action="OnPostAsync" />*@

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

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

<table id="example"  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; }

    }
  •  Tags:  
  • Related