Вы можете попробовать использовать JQuery, чтобы получить список добавленных данных и отправить их на контроллер.
Вот простая демонстрация:
Модель StudentInfo и StudentViewModel
public class StudentInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string FName { get; set; }
public string Class { get; set; }
public string Gender { get; set; }
}
public class StudentViewModel
{
public List<StudentInfo> StudentInfos { get; set; }
}
Контроллер
[HttpPost]
public async Task<IActionResult> InsertStudents([FromBody]StudentViewModel studentVM)
{
List<StudentInfo> model = studentVM.StudentInfos;
_context.AddRange(model);
int insertedRecords=await _context.SaveChangesAsync();
return Json(insertedRecords);
}
Вид
<table id="tblStudents" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width:150px">Name</th>
<th style="width:150px">FName</th>
<th style="width:150px">Class</th>
<th style="width:150px">Gender</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtFName" /></td>
<td><input type="text" id="txtClass" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="button" id="btnAdd" value="Add" /></td>
</tr>
</tfoot>
</table>
<br />
<input type="button" id="btnSave" value="Save All" />
JavaScript
@section Scripts
{
<script type="text/javascript">
$("body").on("click", "#btnAdd", function () {
//Reference the Name and Country TextBoxes.
var txtName = $("#txtName");
var txtFName = $("#txtFName");
var txtClass = $("#txtClass");
var txtGender = $("#txtGender");
//Get the reference of the Table's TBODY element.
var tBody = $("#tblStudents > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(txtName.val());
//Add FName cell.
cell = $(row.insertCell(-1));
cell.html(txtFName.val());
//Add Class cell.
cell = $(row.insertCell(-1));
cell.html(txtClass.val());
//Add Gender cell.
cell = $(row.insertCell(-1));
cell.html(txtGender.val());
//Clear the TextBoxes.
txtName.val("");
txtFName.val("");
txtClass.val("");
txtGender.val("");
});
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var students = new Array();
$("#tblStudents TBODY TR").each(function () {
var row = $(this);
var student = {};
student.Name = row.find("TD").eq(0).html();
student.FName = row.find("TD").eq(1).html();
student.Class = row.find("TD").eq(2).html();
student.Gender = row.find("TD").eq(3).html();
students.push(student);
});
//Populate invoice data
var studentVM = {};
studentVM.StudentInfos = students;
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/StudentInfoes/InsertStudents",
data: JSON.stringify(studentVM),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
</script>
}