我一直试图找出为什么在我的部分视图中提交表单会使我的模型的某些组件为空。就在调用部分视图之前,我有一个模型,ActionWhoms 和 TimesPlaces 的计数均等于 1。
即使使用仅添加一列的简化局部视图,在提交给控制器时,我的 AgainstWhoms 和 TimesPlaces 集合现在都是空的。
public class ComplaintViewModel
{
[Key]
public int Id { get; set; }
.........
public List<AgainstWhomViewModel> AgainstWhoms { get; set; }
public List<TimesPlacesViewModel> TimesPlaces { get; set; }
public List<WitnessesViewModel> Witnesses { get; set; }
}
public async Task<ActionResult> GetNewComplaint(int intComplainantId)
{
var complaint = new ComplaintViewModel
{
ComplainantId = intComplainantId,
StatusId = 1,
ReceivedDate = DateTime.Now,
AgainstWhoms = new List<AgainstWhomViewModel> { },
TimesPlaces = new List<TimesPlacesViewModel> { },
Witnesses = new List<WitnessesViewModel> { }
};
var newtime = new TimesPlacesViewModel { IncidentDate = DateTime.Today, IncidentLocation = "aaaaaaaaa" };
complaint.TimesPlaces.Add(newtime);
var complainee = new AgainstWhomViewModel { CountryId = 1, Email = "aaaaaaa@yahoo.com"};
complaint.AgainstWhoms.Add(complainee);
..................
return PartialView("_ComplaintFormModal", complaint);
}
下面是我的简化视图。
@model ComplaintViewModel
<div>
<form id="Complaintform" asp-controller="Complaint" asp-action="RegisterComplaint" method="post">
<div class="form-row">
<div class="form-group col-lg-8 required">
<label asp-for="ComplaintTitle" class="control-label"></label>
<input type="text" class="form-control" required asp-for="ComplaintTitle">
<span asp-validation-for="ComplaintTitle" class="text-danger"></span>
</div>
</div>
<button type="submit" value="Submit">Submit</button>
</form>
</div>
在我的控制器 post 方法中,newComplaint.AgainstWhom 和 newComplaint.TimePlaces 现在为空,而其他不属于任何链接列表的字段将正确返回:
[HttpPost]
public ActionResult RegisterComplaint(ComplaintViewModel newComplaint)
{
..............