I have a method in CepController RegisterCep that before doing the registration makes some validations and between them, check if there is already a registration for that Cep. I would like to implement a warning to inform the user about the existence of the record without giving a Post on the page.
Controller method:
public IActionResult CadastrarCep(CepViewModel cep)
{
using (var sqlConnection = new SqlConnection(_config.GetConnectionString("DBConect")))
{
if (!ModelState.IsValid)
{
return View("Cadastro", cep);
}
if (cep.TakeCepById(cep.CepCodigo, _config) != null)
{
ModelState.AddModelError("Cep", "Cep já existente.");
// return View("Cadastro", cep);
}
cep.CepSetor = 0;
cep.CepRegiao = "";
cep.CepRota = "";
StringBuilder strSql = new StringBuilder ("INSERT INTO Cep (CepCodigo, CepLogr, CepEnd, CepCompl, CepBairro, CepCidade, CepUF, CepSetor, CepRegiao, CepRota) ");
strSql.Append(" VALUES( @CepCodigo, @CepLogr, @CepEnd, @CepCompl, @CepBairro, @CepCidade, @CepUF, @CepSetor, @CepRegiao, @CepRota)");
sqlConnection.Execute(strSql.ToString(), cep);
return View("Cadastro", new CepViewModel());
}
}
View:
@model WebApplication1.Models.CepViewModel
<h2>Manutenção de Cep</h2>
<div class="container" style="margin-top: 50px;">
<form asp-controller="Cep" asp-action="Cadastro" method="post">
<div class="form-group">
<label class="control-label">CEP</label>
<input asp-for="CepCodigo" maxlength="8" min="8" class="form-control" type="text" />
<span asp-validation-for="CepCodigo" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">LOGRADOURO</label>
<input asp-for="CepLogr" class="form-control" type="text" value="@Model.CepLogr" />
</div>
<div class="form-group">
<label class="control-label">ENDEREÇO</label>
<input asp-for="CepEnd" class="form-control" type="text" value="@Model.CepEnd" />
</div>
<div class="form-group">
<label class="control-label">COMPLEMENTO</label>
<input asp-for="CepCompl" class="form-control" type="text" value="@Model.CepCompl" />
</div>
<div class="form-group">
<label class="control-label">BAIRRO</label>
<input asp-for="CepBairro" class="form-control" type="text" value="@Model.CepBairro" />
</div>
<div class="form-group">
<label class="control-label">CIDADE</label>
<input asp-for="CepCidade" class="form-control" type="text" value="@Model.CepCidade" />
</div>
<div class="form-group">
<label class="control-label">UF</label>
<input asp-for="CepUF" class="form-control" type="text" value="@Model.CepUF" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Consultar" asp-action="ConsultarCep" />
<input type="submit" class="btn btn-default" value="Cadastrar" asp-action="CadastrarCep" />
<input type="submit" class="btn btn-danger" value="Excluir" asp-action="ExcluirCep" />
<input type="submit" class="btn btn-success" value="Alterar" asp-action="AlterarCep" />
</div>
</div>
</div>
</form>