Duplicate field ASP.NET Core MVC

Asked

Viewed 37 times

2

Good morning I am developing a web application and in the registration part I put a CPF field but as it can not be equal to what exists in the bank it of the error, I wanted it to return an error message in the VIEW and not return an error page as below: inserir a descrição da imagem aqui

I implemented Remote validation but it’s not working, as I implement this validation?

Registroviremodel:

[Required(ErrorMessage = "O campo {0} é obrigatorio")]
[Remote("CPFExiste", "Usuario", AdditionalFields = "Id")]
public string CPF { get; set; }

User controller:

public async Task<JsonResult> CPFExiste(string cpf, string Id)

{

if (Id == null) // novo registro

{

if (await _contexto.Usuarios.AnyAsync(x => x.CPF == cpf))

return Json("Exercício já existe");

return Json(true);

}

else // atualização de registro

{

if (await _contexto.Usuarios.AnyAsync(x => x.CPF == cpf && x.Id != Id))

return Json("Exercício já existe");

return Json(true);

}

Record.cshtml:

<script src="~/scripts/jquery.js"></script>
<script src="~/scripts/jquery.validate.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.js"></script>
  • What happens? If you have two Return, why???

  • So, the current error is that of imagen, returns the error page, what I wanted is to return an error message in the registration view itself, example, at the top of the record page "CPF already in use", I asked for help to a teacher and he passed me this code, I’m not sure what the two are about.

1 answer

1


Hello, check in the Startup.Cs class where you are directing errors:

if (env.IsDevelopment())
{
  app.UseDeveloperExceptionPage();
}
else
{
  app.UseExceptionHandler("/Home/Error");
  app.UseHsts();
}

If so use the app.UseExceptionHandler("/Home/Error"); for development and will see a custom page instead of this exception page.

You can also use Tempdata if you only want to display a warning in the View itself in the controller:

  if (ModelState.IsValid)
  {

     if (await _contexto.Usuarios.AnyAsync(x => x.CPF == cpf))
     {
       ModelState.Clear();
       TempData["erro"] = "Já existe um usuário com o mesmo CPF!";
       return View();
     }

     TempData["sucesso"] = "Usuário adicionado!";
     return Json(true);

  }

Na View:

<h4>@TempData["erro"]</h4>
<h4>@TempData["sucesso"]</h4>

Browser other questions tagged

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