Problem deleting a record, fetching the next

Asked

Viewed 68 times

-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?

  • When I go deleting several at once, and even if there are close or previous records, it returns to the new page.

  • 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)

2 answers

1


Your selection logic is a little fuzzy on yours Controller and can be simplified. And I changed your return object Json to ensure that it displays the property and value format and respects the case.

[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;
    }
    //Seleciona o próximo maior
    int? proximoProdutoId = db.Produtos.Select(p => p.Id)
                                        .OrderBy(p => p)
                                        .FirstOrDefault(p => p > id);

    //Se for 0, tenta selecionar o próximo menor
    if(proximoProdutoId == 0)
        proximoProdutoId = db.Produtos.Select(p => p.Id)
                                      .OrderByDescending(p => p)
                                      .FirstOrDefault(p => p < id);


    return Json(new { resultado = result, id = proximoProduto});
}

With these adjustments your javascript should behave in the correct way, but it is worth noting that the way you wrote, if the id entry does not exist in context to be excluded, the resultado will be false and nothing will happen on the page.

  • It returns the following error: The "??" operator cannot be applied to "int" and "int" type operands. E on returnJson, id = next.

  • @marianac_costa, Adjusted

  • I did the tests, and the problem did not occur anymore, thank you.

0

I see two errors being corrected in your logic:

  1. You do not need to use ". Skip(1). Take(1)", because the Firstordefault command preceded by Orderby/Orderbydescending already solves the question of taking the next or the previous one.
  2. In your Ajax call, if the.result date is 'fake', your application will do nothing.

You haven’t made the real problem clear, but maybe it has to do with these two situations.

  • I did the test by removing Skip and take, and nothing happens. I did it this way, because I saw in an answer here in the forum that worked. In the matter of ajax it is false to do nothing, that is how it should be.

Browser other questions tagged

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