skip to Main Content

I have a problem with ajax. I want to send an array of integers that is loaded with several checkboxes. The list loads fine, but when you send it to the controller method it becomes null.

Ajax code:

var ids = new Array();
$(".borrarSeleccionados").on('click', function () {
 console.log("el valor de codigos es " + ids);
 $.ajax({
     type: "POST",
     url: "./BorrarVarios",
     data: {codigos: ids},
 });
});

Method code:

public ActionResult BorrarVarios(long[] codigos)
{
    foreach (int cod in codigos) 
    { 
        var consulta = "DELETE FROM T_INMUEBLES WHERE COD_INMUEBLE = " + cod;
        using (var cmd = cnx.CreateCommand())
        {
            cmd.CommandText = consulta;
            cmd.ExecuteNonQuery();
        }
    }
    return RedirectToAction("Listado", "Inmuebles");
}

3

Answers


  1. Chosen as BEST ANSWER

    problem solved, it was necessary to put contentType: "application/json"

     $.ajax({
           type: "POST",
           url: "./BorrarVarios",
           contentType: "application/json",
           data: JSON.stringify({
           codigos: ids
           })
      });
    

  2. Instead of long data type array try with String data type array in action’s parameter.

    Login or Signup to reply.
  3. I think you just need to stringify your values. MVC will convert that back into an IEnumerable for you.

    var ids = new Array();
    $(".borrarSeleccionados").on('click', function () {
     console.log("el valor de codigos es " + ids);
     $.ajax({
         type: "POST",
         url: "./BorrarVarios",
         data: JSON.stringify({
              codigos: ids
         })
     });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search