dtk*_*k77 3 c# asp.net-core-mvc asp.net-core .net-6.0
这是 dotnet 上的一个示例。github.com/dotnet...我在 net-6.0 版本上工作
验证检查的结果为 false,因为该类的导航属性参与了验证。我在 net-5.0 上实现了一个简单的实验 - 导航属性没有反映在结果中。但是,也许我错了。
如何正确解决这个问题呢?
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Number")]
public int CourseID { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
[Range(0, 5)]
public int Credits { get; set; }
public int DepartmentID { get; set; }
public Department Department { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
public ICollection<CourseAssignment> CourseAssignments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
CoursesController.cs
// POST: Courses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("CourseID,Credits,DepartmentID,Title")] Course course)
{
if (ModelState.IsValid)
{
_context.Add(course);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
PopulateDepartmentsDropDownList(course.DepartmentID);
return View(course);
}
Run Code Online (Sandbox Code Playgroud)
验证结果
我认为问题出在 net6 的一个新的可空特性上。我强烈建议您将其删除或在项目属性中进行评论
<!--<Nullable>enable</Nullable>-->
Run Code Online (Sandbox Code Playgroud)
这是一个非常愚蠢的功能。您必须将所有属性标记为可为空,直到您生命结束。
public ICollection<CourseAssignment>? CourseAssignments { get; set; }
Run Code Online (Sandbox Code Playgroud)
恕我直言,永远不要在控制器操作参数中使用绑定。你总会遇到问题。它仅在 Razor 页面中有用,但在非常非常罕见的情况下有用。在极少数情况下使用 Dto。当我必须从联接创建最多属性时,我通常仅使用 Dto 进行选择。
| 归档时间: |
|
| 查看次数: |
1112 次 |
| 最近记录: |