I am beginner to ASP.NET Core MVC 6.0. Following a tutorial from the Microsoft learning site, I created the "Contoso University" project. In this project, when I add the new student, head to "create new" and input information of on person. It walked one by one.
However, I want to input information of several persons at one time. For example, first I fill several records and click the submit button.
How can I do it?
I can not find my way.
I want to input information of several persons at one time. For example, first I fill several records and click the submit button.
Well, actually, based on your scenario and requirement you should create a list of student object inside the asp form tag helper which require a bit knowledge of javascript.
Within the form you would have a button which would include new dom for student object in the table. Finally, you can post to your controller where you would define list of student as parameter.
Let's have a look in practice, how we can achieve that:
Model:
public class Student
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int Age { get; set; }
}
View:
<form method="post" asp-controller="Student" asp-action="Create">
<div style="padding-bottom:20px">
<button type="button" class="btn btn-primary" onclick="AddNewStudentFunc()">Add New Student</button>
</div>
<div id="dataTable">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="StudenetList" data-count="0">
</tbody>
</table>
</div>
<input type="submit" class="btn btn-success" value="Submit" />
</form>
@section Scripts {
<script>
/*
. I am Hidding table on load
*/
document.getElementById('dataTable').style.display = 'none';
function AddNewStudentFunc() {
var countVal = parseInt($('#StudenetList').attr('data-count'));
var html = '';
html += '<tr>';
html += '<td><input type="text" name="Student[' + countVal + '].FirstName" class="form-control"/></td>';
html += '<td><input type="text" name="Student[' + countVal + '].LastName" class="form-control"/></td>';
html += '<td><input type="text" name="Student[' + countVal + '].Age" class="form-control"/></td>';
html += '</tr>';
$('#StudenetList').append(html);
countVal += 1;
$('#StudenetList').attr('data-count', countVal);
/*
. Showing table when adding item into it
*/
document.getElementById('dataTable').style.display = 'block';
}
</script>
}
Controller:
[HttpPost]
public IActionResult Create(List<Student> student)
{
if (ModelState.IsValid)
{
}
if (!ModelState.IsValid)
{
return View("Create");
}
//Save your student list into database
//_context.Studnet.AddRange(student);
//_context.SaveChangesAsync();
return View("Create");
}
Output:
Note: If you need more details, you could check our official document here.