我正在尝试创建一个具有子项目的实体,并且在来回传递模型方面存在问题。
我有一个包含风险实体列表的实体RiskAssessnent。
public class RiskAssessment
{
public int Id { get; set; }
public DateTime Date { get; set; }
public ICollection<Risk> Risks { get; set; }
public int ResidentId { get; set; }
public Resident Resident { get; set; }
public int EmployeeId { get; set; }
public Employee Employee { get; set; }
}
public class Risk
{
public int Id { get; set; }
public string Description { get; set; }
public int RiskAssessmentId { get; set; }
public RiskAssessment RiskAssessment { get; set; }
}
这是我创建RiskAssessment的观点:
@model CareHomeMvc6.Models.RiskAssessmentViewModels.RiskAssessmentViewModel
@{
ViewData["Title"] = "Create";
}
<a class="btn btn-default" asp-action="Index" asp-route-residentId="@Model.ResidentId">Back to List</a>
<div class="page-header">
<h1>Create a Risk Assessment</h1>
</div>
<form asp-action="Create">
<div class="form-horizontal">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
@Html.HiddenFor(m => m.EmployeeId)
@Html.HiddenFor(m => m.ResidentId)
<div class="form-group">
<label asp-for="Date" class="col-md-2 control-label"></label>
<div class="col-md-10">
@Html.EditorFor(m => m.Date, new { @class = "form-control" })
<span asp-validation-for="Date" class="text-danger" />
</div>
</div>
@foreach(var risk in Model.Risks)
{
<h3>@risk.Description</h3>
}
<p>
<a class="btn btn-success" asp-action="CreateRisk">Create</a>
</p>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
这是控制器:
public IActionResult CreateRisk(RiskAssessmentViewModel riskAssessmentViewModel)
{
var vm = new CreateRiskViewModel
{
RiskAssessment = riskAssessmentViewModel,
Risk = new Risk()
};
return View(vm);
}
和ViewModel:
public class RiskAssessmentViewModel
{
public RiskAssessmentViewModel()
{
this.Risks = new List<Risk>();
this.Risks.Add(new Risk
{
Id = 1,
Description = "blah",
PotentialRisk = "blah"
});
}
public int Id { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
public ICollection<Risk> Risks { get; set; }
public int ResidentId { get; set; }
public int EmployeeId { get; set; }
}
抱歉到目前为止所有的代码!
我试图继续来回传递ViewModel,直到所有项目都已创建,但在CreateRisk操作中,ResidentId和EmployeeId为0,因此没有设置,尽管我确实收到了风险。如果我在包含所有内容的表单上单击“提交”,则会设置它们。是否有任何理由将隐藏的项目发送到表单提交而不是链接操作?
我意识到有JS解决方案来做动态列表,但我想远离它,因为页面导航是可以接受的,表单将在完成时需要大量数据输入风险。
对此的任何帮助将不胜感激。
由于