When field validation is triggered, dropdownlists do not load into Asp.net core MVC

Asked

Viewed 90 times

0

When I start a registration screen, the system loads a ViewModel with the combobox loaded:

inserir a descrição da imagem aqui

If I, for example, click the record button, the fields in my viewmodel are validated, only the page does not keep the combobox loaded.

How to solve this?

inserir a descrição da imagem aqui

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

        [Required(ErrorMessage ="Campo obrigatório")]
        [DisplayName("Nome Completo")]
        public string NomeCompleto { get; set; }

        [DisplayName("Apelido")]
        public string Apelido { get; set; }

        [Required(ErrorMessage = "Campo obrigatório")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        [DataType(DataType.Date, ErrorMessage = "Data em formato inválido")]
        [DisplayName("Nascimento")]
        public DateTime? DataNascimento { get; set; }


        [DisplayName("Sexo")]
        public Sexo Sexo { get; set; }
        [DisplayName("Sexo")]
        public string SexoDescricao { get; set; }
        [DisplayName("Sexos")]
        public IEnumerable<SelectListItem> Sexos { get; set; }


        [DisplayName("Estado Civil")]
        public EstadoCivil EstadoCivil { get; set; }
        [DisplayName("Estado Civil")]
        public string EstadoCivilDescricao { get; set; }
        [DisplayName("Estados Civis")]
        public IEnumerable<SelectListItem> EstadosCivis { 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-2">
            <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>

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

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

            return View(pessoaViewModel);
        }

inserir a descrição da imagem aqui

  • Put the controller!?

  • I just upgraded with the controller.. :)

  • When you click on "record" it is called the method post of your controller; you need to return the object pessoa (or whatever used) to reload in case of error.

2 answers

1


Analyze your code well, I ended up noticing that the object passed is a PessoaFisicaViewModel, and View is signed as PessoaViewModel, apparently the PessoaViewModel does not have the properties of combobox listing (icollection), so when submiting, the conversion of PessoaFisicaViewModel for PessoaViewModel causes these properties to be lost.

  • But that’s the thing.... The Nature Combobox is in Personal Viewmodel and should not give this problem... Something tells me that the problem is in bindings.. ex: <select Asp-for="Personfisicaviewmodel.Statesspeed" Asp-items="Model.PessoaFisicaViewModel.Estadoscivis" class="form-control"> <option value="">-Select-</option> </select> <span Asp-validation-for="Personal Physicaviewmodel.Statevil" class="text-Danger"></span>

  • It is curious, the property <code>Estadoscivis</code>, according to the View, is not in <code>Personal Viewmodel</code> but in a property of <code>Personal Viewmodel</code>, called <code>Personal>.

  • Exactly.... She is part of Personal Bodycaviewmodel. When I Carry the Personal Bodymodel, it comes loaded too.

  • @Jalberromano, wow, now I really understand all the architecture. You have tried renaming the received object in Controller to a name that is not exactly the same as the object class, as just "person"?

  • I tried to.... It still doesn’t work...

  • I discovered the problem: In my Create.cshtml I missed the @Section Scripts { @{await Html.Renderpartialasync("_Validationscriptspartial");} }

  • This caused the problem. afff

  • Thank you to everyone who tried to help me!!! :)

Show 3 more comments

0

In this case, I have the impression that you select the values in the Send Combos to SUBMIT, but since nothing has been saved, the validation is done but the object is returned again by _pessoaAppService.GetJoinById() and in this case, Combo values do not exist in the object returned by this service, and therefore do not return populated.

In my understanding, what you should do is, in the validation, return the validated object and not replace by the returned object by _pessoaAppService.GetJoinById().

  • I had posted the wrong Action (Edit)... I corrected... The correct action is Create. I think I’m missing cshtml.... Because in Actions comboobx arrive with Null (as shown)...

  • @Jalberromano, do you need to use this approach? Don’t you find it more interesting to remove the listing of the Viewmodel object and just put in Viewdata? So you can manipulate with more control, in the Controller methods.

  • Because it is @E.Leal... I have seen models on the net that work like mine having a property viewModel of personFisica within my viewModel of Person... When I do Submit, it seems to be playing null for the Ienumerable<Selectlistitem properties>

  • @Jalberromano about this I see no problem, what I find unusual is popular the listing of the combobox in the object viewModel. I have the impression that these Icolletion are attributes that are not passed by SUBMIT, so they are null.

  • They are populated in my Personal Service... When I create a new Viewmodel it loads there and returns a viewmodel with the loaded combobox. The problem is that Submit is not giving the Post with them loaded... it ends up "setando" with null.

Browser other questions tagged

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