Alex Fariñas
Alex Fariñas

Reputation: 97

How to show html table with ajax from jsonresult on my view

Hello everybody I can't append a table on my view... my jsonresult send the data ok but I have problem to showing on my table... it show the data for 1 milisecond and then looks like the page refresh and show nothing and I don't know why...

On my controller

   [HttpGet] 
    public JsonResult GenerarDetalleInventariobyU(Guid id)
    {
      var result = (from item in bienasignado.GetAll()
                      where item.Ubicacion == id
                      select new
                      {
                          Descripcion = item.Bien.Descripcion,
                          Empleado = item.IdEmpleado

                      }).ToList();

        return Json(result, JsonRequestBehavior.AllowGet);
    }

On my View

function getDetail() {
    var selectedU = $("#UnidadesAdministrativas").val();

    $.ajax({
        cache: false,
        type: "GET",
        url: '@Url.Action("GenerarDetalleInventariobyU", "Inventario")',
        data: { "id": selectedU },
        success: function (data) {
            var tr;
            //Append each row to html table
            for (var i = 0; i < data.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + data[i].Descripcion + "</td>");
                tr.append("<td>" + data[i].Empleado + "</td>");
                $('table').append(tr);

            }
        }
    });
    }

Please help!

Upvotes: 0

Views: 1153

Answers (3)

sam
sam

Reputation: 1985

Another approach (probably easier one) is,

  1. make your action to return PartialView that way, you can craft your view in a .cshtml page. Instead of returning JsonResult, modify it to return PartialView.
  2. onSuccess of your $.ajax call, bind this partial view to any form element like $('#divResults').html(data) where divResults is id of a div (<div id='divResults'></div>) element and data is the return value from your ajax call.

Upvotes: 1

Suyog
Suyog

Reputation: 181

Please add below code in your success function

  $.each(data, function (i, item) {
            $('table').append(
                $('<tr>')
                    .append($('<td>').append(item.Descripcion))
                    .append($('<td>').append(item.Empleado))
            );
            });

Upvotes: 0

Manish Singh
Manish Singh

Reputation: 538

I think you are handling success method in incorrect way.

success: function (data) {
            var tr;
            //Append each row to html table
            for (var i = 0; i < data.length; i++) {
                tr = $('<tr>'); // remove slash from here
                tr.append("<td>" + data[i].Descripcion + "</td>");
                tr.append("<td>" + data[i].Empleado + "</td>");
                tr.append("<tr/>"); // close it here.
                $('table').append(tr);

            }
        }

Upvotes: 0

Related Questions