I would like to understand why when Modelstate is invalid, Viewmodel instantiation is "ignored" and form fields remain populated?

Asked

Viewed 61 times

0

Follows my code:

Subcategory Model

public class SubCategoria
{

    public int Id { get; set; }

    [Required(ErrorMessage = "Campo {0} é obrigatório")]
    [StringLength(200, ErrorMessage = "Campo {0} precisa ter entre {2} e {1} caracteres ", MinimumLength = 2)]
    public string Titulo { get; set; }

    public Categoria Categoria { get; set; }
    public IEnumerable<Livro> Livros { get; set; }
}

Viewmodel of Subcategory:

public class SubcategoriaViewModel
{
    [Required(ErrorMessage = "Campo {0} é obrigatório")]
    [StringLength(200, ErrorMessage = "Campo {0} precisa ter entre {2} e {1} caracteres ", MinimumLength = 2)]
    public string Titulo { get; set; }

    [Required]
    public int CategoriaId { get; set; }
}

Our controller (a part) of "Subcategory"

    // GET: SubCategorias/Create
    public IActionResult Create()
    {
        var vm = new SubcategoriaViewModel();
        ViewData["CategoriaId"] = new SelectList(_context.Categorias, "Id", "Titulo");
        return View(vm);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(SubcategoriaViewModel subCategoriaVM)
    { 
        if (ModelState.IsValid)
        {
            var subcategoria = new SubCategoria
            {
                Titulo = subCategoriaVM.Titulo,
                Categoria = _context.Categorias.FirstOrDefault(m => m.Id == subCategoriaVM.CategoriaId)
            };
            _context.Add(subcategoria);
             await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return Create();

When my Modelstate is invalid, the browser continues on the create screen with the fields filled.

My doubt is about this - how is this possible if in Create() (GET) I always instate a new Viewmodel? If I instate a new Viewmodel, the logic was not to return the empty form?

Anyway... I would like to understand why when Modelstate is invalid the instantiation of Viewmodel is "ignored" and the form fields remain populated?

1 answer

0

Strange, this should only happen if you had to return return View(subCategoriaVM);.

However, you can use the method ModelState.Clear(); that should solve the problem.

Browser other questions tagged

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