My viewbag is showing values correctly at the view, but when the creation control is called the values are null, so since these values are foreign keys in another table, I get an exception:
SqlException: The INSERT statement conflicted with the FOREIGN KEY >constraint "FK_dbo.INFO_APONTAMENTO_dbo.BARCO_Barco_Id". The conflict >occurred in database "RVEIO", table "dbo.BARCO", column 'Id'.
Here is the code:
public ActionResult Create()
{
ViewBag.SubCodigos = new SelectList(_subCodigosOperacionaisRepository.GetAll(), "Id", "Codigo");
ViewBag.Codigos = new SelectList(_codigosOperacionaisService.GetAll(), "Id", "Codigo");
ViewBag.LocalDaOperacao = new SelectList(_localDaOperacaoAppService.GetAll(), "Id", "Nome");
ViewBag.Barcos = new SelectList(_barcoRepository.GetAll(), "Id", "Nome");
return View();
}
[HttpPost]
public ActionResult Create(ApontamentoViewModel apontamentoViewModel)
{
if (!ModelState.IsValid)
{
return View(apontamentoViewModel);
}
ViewBag.Codigos = new SelectList(_codigosOperacionaisService.GetAll(), "Id", "Codigo", apontamentoViewModel.InfoApontamento.CodigosDeOperacao_Id);
ViewBag.SubCodigos = new SelectList(_subCodigosOperacionaisRepository.GetAll(), "Id", "Codigo", apontamentoViewModel.InfoApontamento.SubCodigosDeOperacao_Id);
ViewBag.LocalDaOperacao = new SelectList(_localDaOperacaoAppService.GetAll(), "Id", "Nome", apontamentoViewModel.InfoApontamento.LocalDaOperacao_Id);
ViewBag.Barcos = new SelectList(_barcoRepository.GetAll(), "Id", "Nome", apontamentoViewModel.InfoApontamento.Barco_Id);
var apontamento = _apontamentoAppService.Add(apontamentoViewModel);
}
When the
var apontamento = _apontamentoAppService.Add(apontamentoViewModel);
is called, the value comes null
My View:
<div class="col-md-10">
@Html.DropDownList("Codigos", String.Empty)
@Html.DropDownList("SubCodigos", String.Empty)
@Html.DropDownList("LocalDaOperacao", String.Empty)
@Html.DropDownList("Barcos", String.Empty)
</div>