Save the form so that when it returns an error it does not delete the inputs

0

I am doing a registration system, when the data is correct it saves the bank in a good, when it gives error it returns where it is wrong but it erases everything that was filled or is not viable what I want is that when the user tries to register and the error that he does not have to fill everything again

My post looks like this:

[HttpPost]
public ActionResult CadastroUsuario(UsuarioViewModel model)
{
    UsuarioRepository usuarioRepository = new UsuarioRepository();

    model.Validar();

    if (usuarioRepository.ObterporCpfEmail(model.Email, model.Cpf) != null)
        model.Erros.Add("Email ou Cpf já existe");

    if (model.Erros.Count > 0)
    {
        TipoPessoaRepository tipoPessoaRepository = new TipoPessoaRepository();

        foreach (var moda in tipoPessoaRepository.ObterTodas())
        {
            model.ListaTipoPessoa.Add(new SelectListItem
            {
                Text = moda.Nome,
                Value = moda.IdPessoa.ToString()
            });
        }
        return View(model);
    }

    try
    {
        TipoPessoaRepository tipoPessoaRepository = new TipoPessoaRepository();
        Usuario usuario = new Usuario()
        {
            Cpf = model.Cpf,

            DtCadastro = DateTime.Now,

            Nome = model.Nome,

            Sobrenome = model.Sobrenome,

            TipoPessoa = tipoPessoaRepository.ObterPorId(model.IdPessoa),

            Email = model.Email,

            Senha = model.Senha,
        };

        usuarioRepository.Salvar(usuario);
        return View("Home/Sucesso");
    }

    catch (Exception ex)
    {
        ModelState.AddModelError(string.Empty, "Ocorreu uma falha. Tente novamente mais tarde.");
    }
    return View();
}

My view after returning an error:

    
asked by anonymous 29.12.2017 / 15:20

1 answer

2

Just after the catch block, you are returning the View, without the Model:

try {  } catch (Exception ex)  
{  
ModelState.AddModelError(string.Empty, "Ocorreu uma falha. Tente novamente mais tarde.");  
}  
return View();   // atualizar aqui

Expected:

  

return View (model);

    
29.12.2017 / 15:38