在分部视图中传递给表单的模型返回组件(在调用表单之前不为空)在表单发布到控制器时为 null



我一直在试图找出为什么在我的部分视图中提交表单会使我的模型的某些组件为空。在调用部分视图之前,我有一个模型,其计数分别为 Against stWhoms 和 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.Against stWho和newComplaint.TimePlaces现在为空,而不属于任何链表的其他字段将正确返回:

[HttpPost]
public ActionResult RegisterComplaint(ComplaintViewModel newComplaint)
{
..............

您没有呈现TimesPlaces/AgainstWhoms,因此数据将丢失,因为它们不在表单集合中。

如果要编辑TimesPlaces/AgainstWhoms项,可以像:

@for (int i = 0; i < Model.TimesPlaces.Count; i++)
{
<tr>
<td>
@Html.TextBoxFor(model => model.TimesPlaces[i].IncidentDate)
</td>
<td>
@Html.TextBoxFor(model => model.TimesPlaces[i].IncidentLocation)
</td>
</tr>
}

如果不想编辑它们,可以使用隐藏字段:

@for (int i = 0; i < Model.TimesPlaces.Count; i++)
{
@Html.HiddenFor(model => model.TimesPlaces[i].IncidentDate)
@Html.HiddenFor(model => model.TimesPlaces[i].IncidentLocation)
}

但最好避免这种情况.如果你不想编辑它们,我宁愿再次用ID查询数据库以获取最新的记录,并避免在请求中发布大量数据。

最新更新