如何在ASP.NET Core MVC 6.0中批量提交多条学生记录?
ASP.NET Core MVC 6.0 批量添加学生实现步骤
针对Contoso University项目的批量学生录入需求,可以按以下步骤实现:
1. 创建批量学生视图模型
在项目的Models文件夹下新建BatchStudentViewModel.cs,用来封装多条学生数据:
using ContosoUniversity.Models; using System.Collections.Generic; namespace ContosoUniversity.Models { public class BatchStudentViewModel { public List<Student> Students { get; set; } = new List<Student>(); } }
2. 修改Students控制器
在StudentsController.cs中添加批量创建的Action方法:
using Microsoft.AspNetCore.Mvc; using ContosoUniversity.Data; using ContosoUniversity.Models; public class StudentsController : Controller { private readonly SchoolContext _context; public StudentsController(SchoolContext context) { _context = context; } // GET: Students/BatchCreate public IActionResult BatchCreate() { // 初始化2条空学生数据,方便用户直接录入 var viewModel = new BatchStudentViewModel { Students = new List<Student> { new Student(), new Student() } }; return View(viewModel); } // POST: Students/BatchCreate [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> BatchCreate(BatchStudentViewModel viewModel) { if (ModelState.IsValid) { foreach (var student in viewModel.Students) { // 跳过空数据(比如用户新增了行但没填) if (!string.IsNullOrWhiteSpace(student.LastName) || !string.IsNullOrWhiteSpace(student.FirstName)) { _context.Add(student); } } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(viewModel); } }
3. 批量创建视图
在Views/Students文件夹下新建BatchCreate.cshtml,实现批量录入的表单:
@model ContosoUniversity.Models.BatchStudentViewModel @{ ViewData["Title"] = "批量添加学生"; } <h1>批量添加学生</h1> <form asp-action="BatchCreate"> <div id="students-container"> @for (int i = 0; i < Model.Students.Count; i++) { <div class="student-row mb-4 p-3 border rounded"> <h5>学生 @(i+1)</h5> <div class="form-group"> <label asp-for="Students[i].LastName" class="control-label"></label> <input asp-for="Students[i].LastName" class="form-control" /> <span asp-validation-for="Students[i].LastName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Students[i].FirstName" class="control-label"></label> <input asp-for="Students[i].FirstName" class="form-control" /> <span asp-validation-for="Students[i].FirstName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Students[i].EnrollmentDate" class="control-label"></label> <input asp-for="Students[i].EnrollmentDate" class="form-control" /> <span asp-validation-for="Students[i].EnrollmentDate" class="text-danger"></span> </div> <button type="button" class="btn btn-danger remove-row">删除此行</button> </div> } </div> <button type="button" id="add-student" class="btn btn-primary mb-3">添加新学生</button> <button type="submit" class="btn btn-success">提交所有学生</button> </form> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} <script> // 添加新学生行 document.getElementById('add-student').addEventListener('click', function () { const container = document.getElementById('students-container'); const rows = container.querySelectorAll('.student-row'); const newIndex = rows.length; // 克隆最后一行作为模板 const templateRow = rows[rows.length - 1].cloneNode(true); // 修改所有表单控件的name和id属性,更新索引 templateRow.querySelectorAll('input, label, span').forEach(element => { if (element.hasAttribute('asp-for')) { element.removeAttribute('asp-for'); } const oldName = element.getAttribute('name'); if (oldName) { const newName = oldName.replace(/\[(\d+)\]/, `[${newIndex}]`); element.setAttribute('name', newName); } const oldId = element.getAttribute('id'); if (oldId) { const newId = oldId.replace(/\_(\d+)\_/, `_${newIndex}_`); element.setAttribute('id', newId); } // 清空输入框内容 if (element.tagName === 'INPUT') { element.value = ''; } // 清空验证提示 if (element.classList.contains('text-danger')) { element.textContent = ''; } }); // 更新标题 templateRow.querySelector('h5').textContent = `学生 ${newIndex + 1}`; container.appendChild(templateRow); }); // 删除学生行 document.addEventListener('click', function (e) { if (e.target.classList.contains('remove-row')) { const rows = document.querySelectorAll('.student-row'); if (rows.length > 1) { // 至少保留一行 e.target.closest('.student-row').remove(); } } }); </script> }
4. 访问批量添加功能
运行项目后,访问/Students/BatchCreate即可进入批量录入页面,可点击“添加新学生”增加录入行,填写完成后点击“提交所有学生”即可一次性保存多条数据。
内容的提问来源于stack exchange,提问作者Ali Ali
相关产品推荐
相关产品推荐

