To Send HTML Table from View to Controller in ASP.NET MVC 5

The example in this article shows how to pass table > tbody > tr rows from View to Controller using jQuery AJAX in ASP.NET MVC 5.


The HTML Table rows will be sent as JSON object similar to Model class. To get the HTML table row value, we are going to use jQuery.


Let's consider a table as shown below.


@{
    ViewBag.Title = "Home Page";
}

<div class="row">
    <div class="col-md-4">

        <table class="table" id="tblPersons">
            <thead>
                <tr>
                    <th scope="col">ID</th>
                    <th scope="col">FirstName</th>
                    <th scope="col">LastName</th>
                    <th scope="col">Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Mark</td>
                    <td>Wasson</td>
                    <td>32</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>Jacob</td>
                    <td>Holmes</td>
                    <td>24</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>Larry</td>
                    <td>Kidman</td>
                    <td>18</td>
                </tr>
            </tbody>
        </table>
        <button type="submit" class="btn btn-primary" id="btnSave">Save</button>

    </div>
</div>

As you can see below, an HTML Table is used to display the records.


PassHTMLTableASPNETMVC_1.PNG

Insert multiple rows using AJAX in ASP.NET MVC


When the Save button is clicked, a loop is executed to get all the rows of the HTML Table and a JSON array of the Person class is generated.


namespace PassHTMLTableASPNETMVC.Entities
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

Inside AddPersons Action method, the JSON array of Person records is received as a list as shown below.(HomeController.cs)


public JsonResult AddPersons(List<Person> persons)
{
    //to do something
    string data = "";
    foreach(Person person in persons)
    {
        data += person.FirstName + " " + person.LastName + "\n";
    }
    return Json(data);
}

The id property of the Save button is given the value btnSave. Click event is triggered using jQuery with id property.(_Layout.cshtml)


<script type="text/javascript">
    $("#btnSave").click(function () {

        console.log("btnSave Triggered!");

    });
</script>

When the click event of the btnSave button is triggered, it gives an output to the console of the browser as follows.


PassHTMLTableASPNETMVC_2.PNG

After showing how click event of the Save button works, we can write the part of sending data in our script using AJAX.


<script type="text/javascript">
    $("#btnSave").click(function () {
        console.log("btnSave Triggered!");

        var persons = new Array();
        $("#tblPersons tbody tr").each(function () {
            var row = $(this);
            var person = {};
            person.ID = row.find("td").eq(0).html();
            person.FirstName = row.find("td").eq(1).html();
            person.LastName = row.find("td").eq(2).html();
            person.Age = row.find("td").eq(3).html();
            persons.push(person);
        });

        $.ajax({
            type: "POST",
            url: "/Home/AddPersons",
            data: JSON.stringify(persons),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

PassHTMLTableASPNETMVC_3.PNG

JSON.stringify takes a Javascript object and converts it to string format.


Note:

var obj = {a:1,b:2}


string str = JSON.stringify(obj) returns {"a":1,"b":2} as string


var parse = JSON.parse('{"a":1,"b":2}') makes a Javascript object from string


The JSON array is sent to the Controller using jQuery AJAX and once the response is received, it is displayed using JavaScript Alert Message Box.


PassHTMLTableASPNETMVC_4.PNG

Download the source code.