Problems when giving Post on a Viewmodel to the Controller - Asp.Net Core 2 MVC

Asked

Viewed 257 times

0

I have a Viewmodel that I use to upload data from a natural or legal person. It contains some properties like Personal Properties, among others, that I use to load my dropdownlists from my view. The problem is precisely between my view and my Create method from my Controller. When I give a Post, the properties of my viewmodel get NULL... It seems that when giving the Post, the system clears and arrow the properties that are of type Ienumerable to null. How to solve this????

NOTE: I already posted a similar subject, but the problem was in the Create view when I created a blank viewmodel. I had not inserted a javascript script block.. Please, disregard that post, as this is related to the rescue and is more detailed. When field validation is triggered, dropdownlists do not load into Asp.net core MVC

 public class PessoaViewModel
    {
        [DisplayName("Código")]
        public int Id { get; set; }

        [DisplayName("Natureza")]
        [Required(ErrorMessage ="Escolha uma Natureza")]
        public PessoaNatureza PessoaNatureza { get; set; }
        [DisplayName("Natureza")]
        public string PessoaNaturezaDescricao { get; set; }
        [DisplayName("Naturezas")]
        public IEnumerable<SelectListItem> PessoasNaturezas { get; set; }

        public PessoaFisicaViewModel PessoaFisicaViewModel { get; set; }
        public PessoaJuridicaViewModel PessoaJuridicaViewModel { get; set; }
    }

@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "PessoaFisica";
}

<div class="form-horizontal">
    <div class="form-group">
        <label asp-for="PessoaFisicaViewModel.NomeCompleto" class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <input asp-for="PessoaFisicaViewModel.NomeCompleto" class="form-control" />
            <span asp-validation-for="PessoaFisicaViewModel.NomeCompleto" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaFisicaViewModel.Apelido" class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <input asp-for="PessoaFisicaViewModel.Apelido" class="form-control" />
            <span asp-validation-for="PessoaFisicaViewModel.Apelido" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaFisicaViewModel.DataNascimento" class="col-md-2 control-label"></label>
        <div class="col-md-4">
            <input asp-for="PessoaFisicaViewModel.DataNascimento" class="form-control" />
            <span asp-validation-for="PessoaFisicaViewModel.DataNascimento" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaFisicaViewModel.Sexo" class="col-md-2 control-label"></label>
        <div class="col-md-3">
            <select asp-for="PessoaFisicaViewModel.Sexo" asp-items="Model.PessoaFisicaViewModel.Sexos" class="form-control">
                <option value="">-- SELECIONE --</option>
            </select>
            <span asp-validation-for="PessoaFisicaViewModel.Sexo" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaFisicaViewModel.EstadoCivil" class="col-md-2 control-label"></label>
        <div class="col-md-3">
            <select asp-for="PessoaFisicaViewModel.EstadoCivil" asp-items="Model.PessoaFisicaViewModel.EstadosCivis" class="form-control">
                <option value="">-- SELECIONE --</option>
            </select>
            <span asp-validation-for="PessoaFisicaViewModel.EstadoCivil" class="text-danger"></span>
        </div>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

@using SistemaComercial.Domain.ValueObjects
@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "Cadastrar Nova Pessoa";
}
<div class="panel">
    <div class="panel-heading">
        <h2 class="panel-title">Cadastrar nova Pessoa</h2>
    </div>
    <form asp-action="Create">
        <div class="panel-body container-fluid">
            @* Replacing classic Validation Summary to Custom ViewComponent as TagHelper *@
            <vc:summary />
            <!-- Example Tabs -->
            <div class="example-wrap">
                <div class="nav-tabs-horizontal">
                    <ul class="nav nav-tabs" data-plugin="nav-tabs" role="tablist">
                        <li class="active" role="presentation">
                            <a data-toggle="tab" href="#exampleTabsOne" aria-controls="exampleTabsOne"
                               role="tab">Dados Pessoais</a>
                        </li>
                        <li role="presentation">
                            <a data-toggle="tab" href="#exampleTabsTwo" aria-controls="exampleTabsTwo"
                               role="tab">Documentos</a>
                        </li>
                        <li role="presentation">
                            <a data-toggle="tab" href="#exampleTabsThree" aria-controls="exampleTabsThree"
                               role="tab">Endereços</a>
                        </li>
                        <li role="presentation">
                            <a data-toggle="tab" href="#exampleTabsFour" aria-controls="exampleTabsFour"
                               role="tab">Contatos</a>
                        </li>
                    </ul>
                    <div class="tab-content padding-top-20">
                        <div class="tab-pane active" id="exampleTabsOne" role="tabpanel">
                            <div class="form-horizontal">
                                <div class="form-group">
                                    <label asp-for="Id" class="col-md-2 control-label"></label>
                                    <div class="col-md-2">
                                        <input asp-for="Id" class="form-control" disabled="disabled" />
                                        <span asp-validation-for="Id" class="text-danger"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label asp-for="PessoaNatureza" class="col-md-2 control-label"></label>
                                    <div class="col-md-3">
                                        <select asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" class="form-control">
                                            <option value="">--SELECIONE--</option>
                                        </select>
                                        <span asp-validation-for="PessoaNatureza" class="text-danger"></span>
                                    </div>
                                </div>

                                @if (Model.PessoaNatureza == PessoaNatureza.Fisica)
                                {
                                    @await Html.PartialAsync("_PessoaFisica")
                                }
                                else if (Model.PessoaNatureza == PessoaNatureza.Juridica)
                                {
                                    @await Html.PartialAsync("_PessoaJuridica")
                                }
                                else
                                {
                                    @await Html.PartialAsync("_PessoaFisica")
                                }

                            </div>
                        </div>
                        <div class="tab-pane" id="exampleTabsTwo" role="tabpanel">

                        </div>
                        <div class="tab-pane" id="exampleTabsThree" role="tabpanel">

                        </div>
                        <div class="tab-pane" id="exampleTabsFour" role="tabpanel">

                        </div>
                    </div>
                </div>
            </div>
            <!-- End Example Tabs -->
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    @*<input type="submit" value="Gravar" class="btn btn-success" />
                        <a asp-action="Index" class="btn btn-info">Voltar à Lista</a>*@

                    <button type="submit" class="btn btn-success"><i class="icon wb-check" aria-hidden="true"></i> Gravar</button>

                    <a asp-action="Index" class="btn btn-danger">
                        <span title="Retornar à Lista" class="icon wb-arrow-left"></span> Retornar à lista
                    </a>

                </div>
            </div>
        </div>
    </form>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

[HttpPost]
        [Authorize(Policy = "CanWriteCustomerData")]
        [Route("pessoa-gerenciamento/cadastrar-novo")]
        [ValidateAntiForgeryToken]
        public IActionResult Create(PessoaViewModel pessoaViewModel)
        {
            if (!ModelState.IsValid) return View(pessoaViewModel);
            _pessoaAppService.RegisterPessoaFisica(pessoaViewModel);

            if (IsValidOperation())
                ViewBag.Sucesso = "Pessoa Cadastrada!";

            return View(pessoaViewModel);
        }

@model SistemaComercial.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "PessoaJuridica";
}

<div class="form-horizontal">
    <div class="form-group">
        <label asp-for="PessoaJuridicaViewModel.RazaoSocial" class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <input asp-for="PessoaJuridicaViewModel.RazaoSocial" class="form-control" />
            <span asp-validation-for="PessoaJuridicaViewModel.RazaoSocial" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaJuridicaViewModel.NomeFantasia" class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <input asp-for="PessoaJuridicaViewModel.NomeFantasia" class="form-control" />
            <span asp-validation-for="PessoaJuridicaViewModel.NomeFantasia" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="PessoaJuridicaViewModel.DataAbertura" class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <input asp-for="PessoaJuridicaViewModel.DataAbertura" class="form-control" />
            <span asp-validation-for="PessoaJuridicaViewModel.DataAbertura" class="text-danger"></span>
        </div>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

inserir a descrição da imagem aqui

  • You can put the Partialview code where the combos are?

  • I updated the post @Ricardo Pontual...

  • You are using Asp-for="Personal Physicaviewmodel.Sex", but from the image you have placed, the property that is null is called "Sexes". You have already verified this?

  • Then the question hit me: I have two properties in my viewmodel: public Sex Sex {get; set;} and public iEnumerable<Selectlistitem> Sex {get; set;}... A use for Label and aoutra for Dropdownlist..

1 answer

1


When you put the Model, only what has been associated with the elements in the View with names corresponding to the properties of your Model.

In the code below:

<select asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" class="form-control">
    <option value="">--SELECIONE--</option>
</select>

Who is associated with select is Personal nature, and only he will be posted, Model.Personscontablities was only used to assemble the select and is not associated with any field, so it will not be posted, so it arrives empty.

In such cases, you need to reload these lists in your method Create before returning to the View. One solution is to do this in your builder Model. Another solution, much worse, would be to store Model.Personscontablities in a hidden field, for example <input type='hidden' name='Model.PessoasNaturezas' />

  • @Ricado Punctual thank you so much for the tip!!! Funcionou 100% Criei um construtor para a viewmodel e "setei" os carregamentos... public PessoaViewModel()&#xA; {&#xA; PessoasNaturezas = ExtensaoDeEnumerador.EnumParaSelectListGenerico<PessoaNatureza>("U", PessoaNatureza.ToString()). Orderby(x => x.Text); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.