How to write HTML within the Ajax success

2

I have a project in ASP.NET MVC 4 and in it I have a Ajax request where it calls the controller sending only one parameter. The request does everything correctly, it brings me a list of the data I need.

What I want to know is how I can use this list to write code in Html within success.

Or if I can get the answer from Ajax and use the list in Html out of success.

AJAX Code:

     <script type="text/javascript">
              var item = "";
              $.ajax({
                  type: 'POST', 
                  url: "@Url.Action("_ListaHistorico", "Solicitacoes")", 
                  data: { IdSolicitacao: id}, 
                  dataType: 'JSON', 
                  success: function (result) {
                      for (var i = 0; i <= result.lenght; i++) {
                      }
                  },
                  error: function (msg) {
                      alert("ERRO!");
                  }
              });
          </script>

Controller code:

[HttpPost]
public JsonResult _ListaHistorico(int IdSolicitacao)
{
    List<List<string>> listaHistorico = new List<List<string>>();
    foreach (
        var historico in
            context.Solicitacao.Include("Usuario")
                .Where(x => x.IdSolicitacao == IdSolicitacao)
                .FirstOrDefault()
                .HistoricoSolicitacao.ToList())
    {
        listaHistorico.Add(new List<string>
        {
            historico.DataCadastro.Value.ToShortDateString(),
            historico.Usuario.Nome,
            historico.Observacao
        });
    }

    return Json(listaHistorico, JsonRequestBehavior.AllowGet);
}
    
asked by anonymous 19.03.2014 / 19:56

2 answers

3

You'll have to build the HTML inside the success method using strings, or some template library, and then make a append into some HTML element already on the page.

In addition your controller could be improved to make it easier to work in javascript.

Example:

In your controller, you could return anonymous objects to make it easier to return properties:

[HttpPost]
public JsonResult _ListaHistorico(int IdSolicitacao)
{
    var listaHistorico = context.Solicitacao.Include("Usuario")
        .Where(x => x.IdSolicitacao == IdSolicitacao)
        .FirstOrDefault()
        .HistoricoSolicitacao
        .Select(x => new
        {
            DataCadastro = x.DataCadastro.Value.ToShortDateString(),
            UsuarioNome = x.Usuario.Nome,
            x.Observacao,
        })
        .ToList();

    return Json(listaHistorico, JsonRequestBehavior.AllowGet);
}

In this case, when the object arrived at result of the function assigned to success you would have a json with the following sample structure:

[
    { "DataCadastro": "2014-03-10", "UsuarioNome": "Miguel", "Observacao": "xpto 1" },
    { "DataCadastro": "2014-03-15", "UsuarioNome": "Angelo", "Observacao": "xpto 2" },
]

With this json structure, you can iterate using for , and for each element, read the DataCadastro , UsuarioNome , and Observacao properties. That way, you can then build the string containing the HTML, and finally use the append .

  success: function (result) {
      for (var i = 0; i <= result.length; i++) {
          var item = result[i];
          $("#idDoContainer").append(
              "<div>" +
              "  <div>DataCadastro: " + item.DataCadastro + "</div>" +
              "  <div>DataCadastro: " + item.UsuarioNome + "</div>" +
              "  <div>DataCadastro: " + item.Observacao + "</div>" +
              "</div>"
              );
      }
  },
    
19.03.2014 / 20:03
2

You can use an HTML String and throw it into your document, like this:

          var item = "";
          $.ajax({
              type: 'POST', 
              url: "@Url.Action("_ListaHistorico", "Solicitacoes")", 
              data: { IdSolicitacao: id}, 
              dataType: 'JSON', 
              success: function (result) {
                  var strHTML = "";
                  for (var i = 0; i <= result.length; i++) {
                    strHTML = strHTML + "<li> "+result[i]+"</li>";
                  }
                  strHTML = "<ul>" + strHTML + "</ul>";
                  document.body.innerHTML(strHTML); //transforma o conteudo do body em sua lista
              },
              error: function (msg) {
                  alert("ERRO!");
              }
          });

Very important:

You did not type in% of% correct% would be result.lenght as I used above, if you used result.length in your code, there certainly was an error because of this.

    
19.03.2014 / 20:09