下面是一个示例的解决方法,演示了如何在ASP.NET Core 3.1 MVC中实现多选与对象列表:
创建一个新的ASP.NET Core 3.1 MVC项目。
在Models文件夹中创建两个实体类,一个是主实体类,另一个是关联实体类。例如,我们创建一个Course类和一个Student类。
// Course.cs
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public List Students { get; set; }
}
// Student.cs
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
// CourseController.cs
public class CourseController : Controller
{
public IActionResult Index()
{
// 获取所有课程列表
var courses = GetCourses();
return View(courses);
}
[HttpGet]
public IActionResult Create()
{
// 获取所有学生列表
var students = GetStudents();
// 创建一个空的课程对象
var course = new Course();
// 将学生列表传递给视图
ViewBag.Students = students;
return View(course);
}
[HttpPost]
public IActionResult Create(Course course)
{
// 保存课程对象到数据库
return RedirectToAction("Index");
}
private List GetCourses()
{
// 返回从数据库中获取的课程列表
return new List
{
new Course { Id = 1, Name = "Course 1" },
new Course { Id = 2, Name = "Course 2" },
new Course { Id = 3, Name = "Course 3" }
};
}
private List GetStudents()
{
// 返回从数据库中获取的学生列表
return new List
{
new Student { Id = 1, Name = "Student 1" },
new Student { Id = 2, Name = "Student 2" },
new Student { Id = 3, Name = "Student 3" }
};
}
}
@model List
课程列表
课程ID
课程名称
@foreach (var course in Model)
{
@course.Id
@course.Name
}
@model Course
创建课程
这个示例演示了如何在ASP.NET Core 3.1 MVC中实现多选与对象列表。当创建课程时,可以选择相关的学生,并将课程对象保存到数据库中。在Course/Index页面中可以查看已创建的课程列表。