I want to send html table rows to ASP.NET MVC controller

Moaz mohamed 0 Reputation points
2023-11-15T17:04:19.4366667+00:00

I want to send html table rows to ASP.NET MVC controller.

This is the table I want to send it to the controller:

@model System.Data.DataTable
@{
    ViewData["Title"] = "Index1";

}
<form asp-action="Index" method="get">

    <div class="form-group">
        <label for="SearshString">Type Barcode :</label>

        <input type="text" name="searshstring" />

        <input type="submit" value="Search" class="btn btn-primary" />
    </div>
    <div id="printableTable">
            <table id="printTable" class="table table-bordered table-striped">
                <tr>
                    <th scope="col">Barcode</th>
                    <th scope="col">Itemname</th>
                    <th scope="col">SelPrice</th>
                    <th scope="colgroup">Quantity</th>
                    <th scope="colgroup">DEL</th>
                    <th scope="colgroup">ADD</th>
                    <th scope="colgroup">MINUS</th>
                </tr>
                @if (Model != null)
                {
                    @for (int i = 0; i < Model.Rows.Count; i++)
                    {
                        <tr>

                             <td>@Model.Rows[i][0]</td>
                            <td>@Model.Rows[i][1]</td>
                            <td>@Model.Rows[i][2]</td>
                            <td>1</td>
                            <td><a class="btn btn-danger" href="@Url.Action("Delete","Sales",new { @barcode=@Model.Rows[i][0]})">Delete</a></td>
                            <td><button type="button" class="btn btn-primary" onclick="addQuantity(this); ">Add Quantity</button></td>
                            <td><button type="button" class="btn btn-info" onclick="minusQuantity(this); ">Minus Quantity</button></td>

                        </tr>
                    }
                }
            </table>
    </div>
</form>

I want to create a button and when I click on it, the table rows should be sent to the ASP.NET MVC controller in a method.

I want to send it to save it in the database.

Please tell me how can I do this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,199 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,281 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,292 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Lan Huang-MSFT 25,866 Reputation points Microsoft Vendor
    2023-11-16T08:58:42.1766667+00:00

    Hi @Moaz mohamed,

    Your view only uses a simple Html table, so you need to use the AJAX POST method to transfer the table rows to the ASP.NET MVC controller.

    Details can be found in the code below(My example uses test data, you can change the Thing class to suit your own needs.).

    @model System.Data.DataTable
    @{
        ViewData["Title"] = "Index1";
    
    }
    <form asp-action="Index" method="get">
    
        <div class="form-group">
            <label for="SearshString">Type Barcode :</label>
    
            <input type="text" name="searshstring" />
    
            <input type="submit" value="Search" class="btn btn-primary" />
        </div>
        <div id="printableTable">
            <table id="printTable" class="table table-bordered table-striped">
                <tr>
                    <th scope="col">Barcode</th>
                    <th scope="col">Itemname</th>
                    <th scope="col">SelPrice</th>
                    <th scope="colgroup">Quantity</th>
                    <th scope="colgroup">DEL</th>
                    <th scope="colgroup">ADD</th>
                    <th scope="colgroup">MINUS</th>
                </tr>
                @if (Model != null)
                {
                    for (int i = 0; i < Model.Rows.Count; i++)
                    {
                        <tr>
    
                            <td>@Model.Rows[i][0]</td>
                            <td>@Model.Rows[i][1]</td>
                            <td>@Model.Rows[i][2]</td>
                            <td>1</td>
                            <td><a class="btn btn-danger" href="@Url.Action("Delete","Sales",new { @barcode=@Model.Rows[i][0]})">Delete</a></td>
                            <td><button type="button" class="btn btn-primary" onclick="addQuantity(this); ">Add Quantity</button></td>
                            <td><button type="button" class="btn btn-info" onclick="minusQuantity(this); ">Minus Quantity</button></td>
    
                        </tr>
                    }
                }
            </table>
            <button id="buttonID" title="ad action">Add</button>
        </div>
    </form>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $("#buttonID").click(function () {
            let table = document.querySelector('#printTable');
            let product = "";
            const data = [];
            let headers = [...table.rows[0].cells].map(th => th.innerText);
            for (let row of [...table.rows].slice(1, table.rows.length)) {
                product = Object.fromEntries(new Map([...row.cells].map((cell, i) => [headers.at(i), cell.innerText])));
                data.push(product);
            }
            var things = data;
            things = JSON.stringify({ 'things': things });
    
            $.ajax({
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                type: 'POST',
                url: '/Home/Index',
                data: things,
                success: function () {
                    console.log("SUCCESS")
                },
                failure: function (response) {
    
                }
            });
        });
    </script>
    
    public ActionResult Index()
            {
                DataTable dt = new DataTable("MyTable");
                dt.Columns.Add(new DataColumn("Col1", typeof(string)));
                dt.Columns.Add(new DataColumn("Col2", typeof(string)));
                dt.Columns.Add(new DataColumn("Col3", typeof(string)));
    
                for (int i = 0; i < 3; i++)
                {
                    DataRow row = dt.NewRow();
                    row["Col1"] = "col 1, row " + i;
                    row["Col2"] = "col 2, row " + i;
                    row["Col3"] = "col 3, row " + i;
                    dt.Rows.Add(row);
                }
    
                return View(dt);
            }
            [HttpPost]
            public ActionResult Index(List<Thing> things)
            {
                //foreach (Thing i in things)
                //{
                //    DB.Customers.Add(new Thing
                //    {
                //        Barcode = i.Barcode,
                //        Itemname = i.Itemname,
                //        SelPrice = i.SelPrice,
                //        Quantity = i.Quantity,
                //    });
                //}
                //DB.SaveChanges();
                return View(things);
            }
    
            public class Thing
            {
                public string Barcode { get; set; }
                public string Itemname { get; set; }
                public string SelPrice { get; set; }
                public int Quantity { get; set; }
            }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Bruce (SqlWork.com) 56,846 Reputation points
    2023-11-16T23:32:18.9533333+00:00

    you could change the form action to post. then add a hidden field for each td item. but this is a bad practice because the user can edit the values and hack your site. on postback the server should recreate the data and insert.

    0 comments No comments