0

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>
sri harsha
  • 676
  • 6
  • 16
AllMuch
  • 29
  • 7
  • 1
    This has been asked multiple times in Stackoverflow. ViewBag is intended to pass values from the controller to the view and that's it. The values are not going to persist till the next request. If you want them to persists then use TempData. Also in Create method by POST, when model state is valid you're not returning. – derloopkat Jan 21 '19 at 16:55
  • Possible duplicate of [What is the difference between ViewData, ViewBag and TempData?](https://stackoverflow.com/questions/28299365/what-is-the-difference-between-viewdata-viewbag-and-tempdata) – derloopkat Jan 21 '19 at 16:57

0 Answers0