将数据从表单传递到控制器时,该值始终为null。视图模型包含需要显示和使用的4种不同模型,但是当尝试将其绑定回发布时,没有任何内容被发布回控制器。仅在使用时间表模型时有效,但是在视图模型中使用时间表对象时,属性始终为空。
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> TimeTable([Bind("TeacherId,DateOfLesson,SubjectDetails,Test")]CourseViewModel timeTable)
{
if (ModelState.IsValid)
{
_context.Add(timeTable.ClassTime);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(TimeTable));
}
return View(timeTable);
}
ViewModel:
public class CourseViewModel
{
public IEnumerable<IndividualSubject> individualSubjects { get; set; }
public IEnumerable<Course> Courses { get; set; }
public IEnumerable<Student> User { get; set; }
public TimeTable ClassTime { get; set; }
public List<DateTime> CalDateTimes = new List<DateTime>();
}
查看:
<table class="table table-hover table-dark">
<thead></thead>
<tbody>
@foreach (var item in Model.CalDateTimes)
{
<tr>
<th scope="row" style="width: 25%" class="border-right">
@item.Date.ToString("dddd dd MMM yyyy")
</th>
<td style="width: 75%">
<form asp-controller="IndividualSubjects" asp-action="TimeTable" method="post" role="form">
<input type="hidden" value="2" asp-for="ClassTime.TeacherId" name="TeacherId" />
<input type="hidden" value="@item" asp-for="ClassTime.DateOfLesson" />
<input type="hidden" value="200" asp-for="ClassTime.Duration" />
<select class="form-control border-dark custom-select-sm float-left" id="monthSelection" style="width: 20%" asp-for="ClassTime.SubjectDetails">
@foreach (var subjects in Model.individualSubjects)
{
<option value="@subjects.SubjectId">@subjects.Name</option>
}
</select>
<input type="submit" value="Add lesson" class="btn btn-primary float-right" />
</form>
</td>
</tr>
}
</tbody>
</table>