Call the controller via javascript or ajax and insert in table Asp.net mvc

Asked

Viewed 655 times

0

How can I get an item from ul li pass its value(id) to my controller and insert that value into the table?

I already have the list this chunk of code below already works I can add items in the list and see text and value:

            $("#addPeca").click(function () {
            //Váriavel para checar se já existe na lista
            var jaExisteNaLista = false;
            $(".listasDasPecas").show();

            $('#ListPeca li').each(function () {
                haveSomeLi = true;
                var current = $(this).text();
                if (current == $("#Pecas option:selected").text()) {
                    jaExisteNaLista = true;
                }
            });

            if (!jaExisteNaLista) {
                $("#ListPeca").append("<li>" + $("#Pecas option:selected").text() + "<input type='checkbox' name='chkPeca' id='chkPeca' class='chkPeca' checked='checked' value='" + $("#Pecas option:selected").val() + "'></li>");
            } else {
                alert("Peca Já inserida!");
            }
        });

Now I want to take what comes from this read and when you click add already calls my controller "addPeca" and makes the Insert in the table according to id that I read. so I’ve done my controller like this so far, but I’m kind of lost:

    [HttpPost, ActionName("Detalhes")]
public ActionResult AddPecas(int id)
{

    using (Db db = new Db())
    {

        var lstPeca = Request.Form["chkPeca"];

        if (!string.IsNullOrEmpty(lstPeca))
        {
            //cria array de peças vindo do form
            int[] splTags = lstPeca.Split(',').Select(Int32.Parse).ToArray();

            if (splTags.Count() > 0)
            {
                //verifica id
                var PostPeca = db.Pecas.Where(p => splTags.Contains(p.Id));

                ConsertoDetalhes consDetalhe = new ConsertoDetalhes();

                // Add para ConsertoDetalhe
                foreach (var item in PostPeca)
                {
                    consDetalhe.ConsertoId = consertoId;
                    consDetalhe.ClienteId = clientId;
                    consDetalhe.PecasId = item.Id;//pecaID
                    consDetalhe.FuncionarioId = funcId;
                    consDetalhe.ValorTotal = item.ValorUnitatio;

                    db.ConsertoDetalhes.Add(consDetalhe);
                    db.SaveChanges();
                }

            }
        }

    }

    return View();
}
  • Just to clarify you will send a list of ids to der registered in the base, or will, send only one id per click?

2 answers

1

Look, I think this is not possible! It could be inserted in SQL files and tables. But in ASP.NET table, I do not know...

0

From what I understand you want to insert a new record in the database, but one thing I did not understand, is what information will be registered in the bank, passing only one id ?

'Cause usually when we pass idis to retrieve an already registered data, to alter, manipulate or just display.

In your case you have to send an object with all values filled in, values that your bank will need to create the record.

to request to the server via javascript you can use the ajaxwhich makes asynchronous requests to the server.

You can do it this way.

$.post(url, objetoComOsDados, function(resp){
    //Caso seu servidor retorne success, vem para aqui.
    alert("Cadastro realizado com sucesso");
})
.fail(function(error){
    //Caso de erro vem para aqui.
    console.log(error);
});

Already on the server, the best practice is to create a model with the data that will be needed to insert in the database, and wait for this model as parameter of your Action.

public ActionResult AddPecas(PecaModel model)
{
    //Caso queira validar o medelo antes de inserir.

    using(var db = new Contex())
    {
         db.Pecas.add(model);
         try
         {
             db.SaveChange();
             return Json(new {status = true});
         }
         catch(Exception e)
         {
              //Tratar o erro.
              return Json(new {status = false});
         }
    }
}

Remembering that it is just an example your controller can make all the logic necessary for your application, as it is an asynchronous call with java script always return a json in response.

Browser other questions tagged

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