Reputation: 33
i'm new with automapper and i have a problem with navigation properties mapping. I have create a map like this :
CreateMap<ObjEntity, ObjEntityViewModel>()
.ForMember(dest => dest.LabelName,
opts => opts.MapFrom(src => src.IdNavigation.LabelName)).ReverseMap();
it made a flat object and it works fine. But when i post back ObjEntityViewModel from my Edit Form, the property "LabelName" is always null. It appears all properties define with ForMember always null when it post back from my html form. I don't understand why is it null and how can i resolve this problem.
My controller code :
public MesObsIndividusController(IMapper mapper)
{
_mapper = mapper;
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return new NotFoundViewResult("NotFound");
}
var mesObsIndividus = await _observationService.GetMesObsindividus(id.Value);
if (mesObsIndividus == null)
{
return new NotFoundViewResult("NotFound");
}
//mapping du ViewModel
var mesVM = _mapper.Map<ObjEntityViewModel>(mesObsIndividus);
return (mesVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ObjEntityViewModel mesObsIndividus)
{
if (id != mesObsIndividus.IdMes)
{
return new NotFoundViewResult("NotFound");
}
if (ModelState.IsValid){
//do update database stuff
}else
{
return View(mesObsIndividus);
}
return RedirectToAction(nameof(Details), new { id = mesObsIndividus.IdMes });
}
My html code :
@model Proj.Models.ObjEntityViewModel
<form asp-action="Edit">
<input type="hidden" asp-for="IdMes" />
<div class="form-group">
<label asp-for="LibEspece" class="control-label"></label>
<input asp-for="LibEspece" id="LbEspece" class="form-control" />
<span asp-validation-for="LibEspece" class="text-danger"></span>
</div>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.LabelName)
</dt>
<dd>
@Html.DisplayFor(model => model.LabelName)
</dd>
</dl>
<div class="form-group">
<input type="submit" value="Enregistrer" class="btn btn-primary" />
</div>
</form>
Thank's
I use EF core 2.2 and automapper 6.0.0
Upvotes: 0
Views: 364
Reputation: 969
Your problem is that you don't persist the LabelName in your form.
Using @Html.DisplayNameFor(model => model.LabelName)
or @Html.DisplayFor(model => model.LabelName)
is not generating input tags from which the value of LabelName can be 'collected' by submission of the form.
You have to have something like this in your form:
<input type="hidden" asp-for="LabelName" />
Upvotes: 1