In ASP.NET Core MVC using EF Core 6, I have the following problem:
[HttpPost] Create()
gets the applicant object (Master) correctly,
but applicant.Experiences
(detail) is empty. Maybe I missed something in binding detail?
I use "EF Core Power Tools" to generate the model.
Thanks for your help.
Controller:
public class ResumeController : Controller
{
[HttpGet]
public IActionResult Create()
{
Applicant applicant = new Applicant();
applicant.Experiences.Add (new Experience() { ExperienceId = 1 });
applicant.Experiences.Add(new Experience() { ExperienceId = 2 });
applicant.Experiences.Add(new Experience() { ExperienceId = 3 });
return View(applicant);
}
[HttpPost]
public IActionResult Create(Applicant applicant)
{
//***********Error***************
//applicant.Experiences.count = 0 , Should be 3
//********************************
_context.Add(applicant);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
Model classes:
public partial class Applicant
{
public Applicant()
{
Experiences = new List<Experience>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Experience> Experiences { get; set; }
}
public partial class Experience
{
public int ExperienceId { get; set; }
public int ApplicantId { get; set; }
public string FieldName { get; set; }
public virtual Applicant Applicant { get; set; }
}
View:
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Experiences.Count; i++)
{
<tr>
<td>
@Html.EditorFor(x => x.Experiences[i].FieldName, new {htmlAttributes = new {@class = "form-control"}})
</td>
</tr>
}
</tbody>
</table>
Your table is outside of the posted form so it will not be included in the form data posted. Move it inside the form
tag (and adjust the html accordingly).
P.S.
In general try avoiding using Entity Framework entities as models, create special DTOs and map between them, this will solve quite a lot of issues, including overposting attacks.