Load a table dynamically with ajax

1

I am trying to mount a table by making a request to the server and populating it with the return.

The return of the server is correct, but when it enters the function(data) , I noticed that it loads all my html page, I already tried to play the ajax direct in $(document).ready , and then use the form it is in below, using load , but neither is working.

$("#table_horde").Load(
     $.ajax({
         type: "POST",
         url: "/Horde/List/",
         success: function (data) {

             var cols = "";

             for (var i = 0; i < data.length; i++) {
                 cols += "<tr>";
                 cols += "<td>" + data[i].NomeHorda + "</td>";
                 cols += "<td>" + data[i].Limit + "</td>";
                 cols += "<td><a href='#' onclick='atualizar'(" + data[i].IdHorde + ")' data-target='#janelaHordaCadastro' data-toggle='modal'>Atualizar</a></td>";
                 cols += "<td><a href='#' onclick='excluir'(" + data[i].IdHorde + ")'>Excluir</a></td>";
                 cols += "</td>";
             }

             $("#table_horde tbody").empty();
             $("#table_horde tbody").append(cols);
             $("#qtdRegistro").html(data.length);
         },
         error: function (ex) {
             alert("Erro: " + ex.status);
         }
     })
);

My Controller is as follows:

public ActionResult List() { 
    return View("List", ListinerHorde()); 
} 

private List<HordeList> ListinerHorde() {
  var list = new List<HordeList>();
  HordeRepository hr = new HordeRepository(); 

  foreach (var h in hr.FindAll()) {
   var model = new HordeList(); 
   model.NameHorde = h.NameHorde; 
   model.Limit = h.Limit; 
   list.Add(model); 
  } 

  return list; 
} 

See below the return image:

    
asked by anonymous 03.05.2017 / 17:57

1 answer

2

In your Controller you are returning a View , but in your Ajax you are expecting a list.

One solution would be to just return the list to View , so create an Action to return the JSON. In this case I have called ListaJson() just to understand you better, but you can put whatever name you want.

public ActionResult ListaJson() { 
     var lista = ListinerHorde();
     return Json(lista , JsonRequestBehavior.AllowGet);
} 

This will only change the URL of your Ajax , like this:

 url: "/Horde/ListaJson/",

Now, if you want to return to View , you do not need to mount the table on the front end, but add the returned HTML, an example would be this:

$.ajax({
     type: "POST",
     url: "/Horde/List/",
     success: function (data) {
        //Coloque aqui o local onde a View deverá ocupar
        $("#table_horde").html(data);
     },
     error: function (ex) {
         alert("Erro: " + ex.status);
     }
});

Just remember to change $("#table_horde").html(data); to where View should occupy.

    
03.05.2017 / 18:54