Home > database >  ASP.Net MVC Sending Table data from view to controller
ASP.Net MVC Sending Table data from view to controller

Time:09-13

I have a table in my view for what is essentially my attempt at making a timesheet table. It also contains a button for adding more rows to the table.

<table  id="mytab" cellspacing="0" cellpadding="0">  
        <thead>
            <tr>  
                <th>Project</th>   
                <th>Discipline</th>  
                <th>Mo</th>  
                <th>Tu</th>  
                <th>We</th>  
                <th>Thu</th>  
                <th>Fri</th>  
                <th>Sat</th>  
                <th>Sun</th>  
                <th></th>
            </tr>  
        </thead>
        <tr>
            <td><select name="selectedProjectId" asp-items="@ViewData["projectSubProject"] as SelectList" >
            </select></td>  
            <td><select name="selectedPositionId" asp-items="@ViewData["Positions"] as SelectList" ></select></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td>  
            <td><input  type="number" min="1" max="24"/></td> 
        </tr>
    </table> 
    <br />
    <form action="">
        <input type="button" value="Add a Row" onclick="addRow()">
    </form>

enter image description here enter image description here enter image description here

You may change your code like this:

@section Scripts{
    <script>
        $("#btn1").click(function(){
            var data = [];
            var row1 = [1, 2, 3, 4, 5];
            var row2 = [6,7,8,9,10];
            data.push(row1);
            data.push(row2);
            $.ajax({
                url: "https://localhost:7175/Home/TableList",
                type: "post",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data);
                }
            });
        });
    </script>
}

[HttpPost]
//[ValidateAntiForgeryToken]
public string TableList([FromBody]List<object> data)
{
    //if (ModelState.IsValid) { 
    //    var list = JsonConvert.DeserializeObject(json);
    //}
    return "hello";
}
  • Related