Save the form so that when returning an error it does not erase the inputs

Asked

Viewed 27 times

0

I’m making a registration system, when the data is correct he saves in the bank in a good, when it gives error it returns where it is wrong but it erases everything that has been filled or is not feasible what I want is that when the user tries to register and error 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 it returns some error:inserir a descrição da imagem aqui

1 answer

2

Right after the block catch, you are returning to 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);

Browser other questions tagged

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