-1
I am trying to do in the code, a page edit, then the user on this page edit, he can delete the record, and if he delete, the system has to check, if there is a record next, it goes to edit screen next, if there is no id next, he tries the previous record, and if he has neither the next nor the previous one, he returns to the page to include a new one. Follow the logic I’m making, but it doesn’t always work.
[HttpPost]
public ActionResult ExcluirProduto(int id)
{
var result = false;
var item = db.Produtos.Find(id);
if (item != null)
{
db.Produtos.Remove(item);
db.SaveChanges();
result = true;
}
var itemProx = db.Produtos.Where(e => e.Id >= id).OrderBy(e => e.Id).Skip(1).Take(1).FirstOrDefault();
var itemAnte = db.Produtos.Where(e => e.Id <= id).OrderByDescending(e => e.Id).Skip(1).Take(1).FirstOrDefault();
int idprox = 0;
int idant = 0;
try
{
idprox = itemProx.Id;
}
catch { idprox = 0; }
try
{
idant = itemAnte.Id;
}
catch { idant = 0; }
try
{
if (idprox == 0 && idant == 0)
{
id = 0;
}
else
{
if (idprox != 0)
{
id = (itemProx.Id);
}
else
{
id = (itemAnte.Id);
}
}
return Json(new { Resultado = result, id });
}
catch {
id = 0;
return Json(new { Resultado = result, id });
}
}
And here is my AJAX that redirects the page:
function Excluir(idproduto) {
var idproduto = document.getElementById("Id").value;
var url = "/Produto/ExcluirProduto";
$.ajax({
url: url,
data: { id: idproduto },
datatype: "json",
type: "POST",
success: function (data) {
if (data.resultado) {
alert('Excluído com sucesso.');
if (data.id != 0) {
window.location.href = "/Produto/Editar/" + (data.id);
}
else {
window.location.href = "/Produto/Novo";
}
}
}
})
}
Remembering that I use MVC Core - Page Razor.
When it doesn’t work?
– Leandro Angelo
When I go deleting several at once, and even if there are close or previous records, it returns to the new page.
– Mariana
Missing details of what is wrong the question is long. Try to edit it to get useful answers. As a contribution, use
console.log
in the date.result to check, probably a negative value is coming (Undefined, 0, null, "", etc)– LeonanCarvalho