DropDown List, problem to save value, returning null object

um using DDD in my project, and im having problems to use dropdowns

I can already load the data of the class "ClasseBarco" in the dropdown, but I cannot save the choice in the database

The "BarcoViewModel" class has the 1-to-many relationship with the class "ClasseBarcoViewModel". When I try to save the chosen option in the dropdown, I get the following error: "classeBarco was null". Using a EditorFor I can save, I just cannot save when I use the dropdown

ViewmodeClass that call other 3 class's

public class BarcoClasseViewModel


{
    public BarcoViewModel Barco { get; set; }

    public ClasseBarcoViewModel ClasseBarco { get; set; }

    public TipoOperacaoDoBarcoViewModel TipoOperacaoDoBarco{ get; set; }

   }

ViewModeBarco

   public class BarcoViewModel
   {
     public BarcoViewModel()
     {
        Id = Guid.NewGuid();
    }


    [Key]
    public Guid Id { get; set; }

    [Required(ErrorMessage = "Campo Obrigatório")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "Campo Obrigatório")]
    public bool Ativo { get; set; }

    [Display(Name = "Registro SAP")]
    [Required(ErrorMessage = "Campo Obrigatório")]
    public int SapId { get; set; }

    [Display(Name = "Tancagem Água")]
    [Required(ErrorMessage = "Campo Obrigatório")]
    public int CapacidadeAgua { get; set; }

    [Display(Name = "Tancagem óleo")]
    [Required(ErrorMessage = "Campo Obrigatório")]
    public int CapacidadeOleo { get; set; }


    [Required(ErrorMessage = "Campo Obrigatório")]
    public int Velocidade { get; set; }

    [Required(ErrorMessage = "Preencha o campo E-mail")]
    [MaxLength(100, ErrorMessage = "Máximo {0} caracteres")]
    [EmailAddress(ErrorMessage = "Preencha um E-mail válido")]
    [Display(Name ="E-mail")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Campo Obrigatório")]
    public string Setor { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DataCadastro { get; set; }

    [ScaffoldColumn(false)]
    public bool Excluido { get; set; }

    [ScaffoldColumn(false)]
    public int ClasseBarcoId { get; set; }

    [ScaffoldColumn(false)]
    public ClasseBarcoViewModel classeBarco { get; set; }

    [ScaffoldColumn(false)]
    public TipoOperacaoDoBarcoViewModel TipoOperacaoDoBarco { get; set; }

    [ScaffoldColumn(false)]
    public DomainValidation.Validation.ValidationResult ValidationResult { get; set; }

}

}

ViewModelClasseBarco public class ClasseBarcoViewModel {

    public ClasseBarcoViewModel()
    {
        Id = Guid.NewGuid();
    }

    [Key]
    public Guid Id { get; set; }

    [Display(Name ="Classe")]  
    [Required(ErrorMessage ="Campo Obrigatório")]
    public string Nome { get; set; }

    [ScaffoldColumn(false)]
    public bool Ativo { get; set; }


    [ScaffoldColumn(false)]
    public DateTime DataCadastro { get; set; }

    [ScaffoldColumn(false)]
    public Guid ClasseBarcoId { get; set; }

}

CONTROLLER

      [Authorize(Roles = "Administrator")]
      [Route("criar-novo")]
       public ActionResult Create()
      {
        ViewBag.ClasseBarcoId = new   SelectList(_barcoAppService.ObterTodasAsClasses(), "ClasseBarcoId", "Nome");

        return PartialView();
    }

    // POST: Barcos/Create
    [Authorize(Roles = "Administrator")]
    [Route("criar-novo")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(BarcoClasseViewModel barcoClasseViewModel)
    {
        if (!ModelState.IsValid) return PartialView(barcoClasseViewModel);

        ViewBag.ClasseBarcoId = new SelectList(_barcoAppService.ObterTodasAsClasses(), "ClasseBarcoId", "Nome", barcoClasseViewModel.Barco.ClasseBarcoId);

        var barcoEnd = _barcoAppService.Add(barcoClasseViewModel);


        if (barcoEnd.Barco.ValidationResult.IsValid) return RedirectToAction("Index");

        PopularModelStateComErros(barcoEnd.Barco.ValidationResult);


        return PartialView(barcoClasseViewModel);


    }

view

 <div class="form-group">
              @Html.LabelFor(model => model.Barco.ClasseBarcoId,   htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-3">
                @Html.DropDownList("ClasseBarcoId", String.Empty)
                @Html.ValidationMessageFor(model => model.Barco.ClasseBarcoId, "", new { @class = "text-danger" })
            </div>
        </div>

1 answer

  • answered 2018-10-11 19:56 Victor Laio

    You have to delegate new classes in constructor, because if your property is not set you will got the exception at get values.

    public class BarcoClasseViewModel
    
    public BarcoClasseViewModel()
    {
      Barco = new BarcoViewModel();
      ClasseBarco = new ClasseBarcoViewModel();
      TipoOperacaoDoBarco = new TipoOperacaoDoBarcoViewModel();
    }
    
    {
      public BarcoViewModel Barco { get; set; }
      public ClasseBarcoViewModel ClasseBarco { get; set; }
      public TipoOperacaoDoBarcoViewModel TipoOperacaoDoBarco{ get; set; }
    }