How to write HTML inside Ajax Success

Asked

Viewed 1,318 times

2

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

What I want to know is how can I use this list to write a code on Html within the Success.

Or if I can get the answer from Ajax and use the list in Html outside the 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);
}
  • Just to warn you, you missed the entry on result.lenght the correct would be result.lenght, I’ve already edited. If you put it in the code this way, this would be a problem ^^

  • @Pauloroberto I don’t know if this edition was a good idea, it seems unlikely that the author was writing the letter by letter, line by line the code to put it in the question... It is more likely that it was copy&paste and that the typo is being the problem / a problem he is having.

  • @Zuul you’re right, I went back.

  • The syntax was really wrong. Thank you for correcting.

2 answers

3


You will have to build HTML within the method success using strings, or some template library, and then making a append in some HTML element that is already on the page.

In addition your controller could be improved in order to facilitate the work in javascript.

Example:

In your controller, you could return anonymous objects in a way that makes 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 the result of the function assigned to the success you would have a json with the following example 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 a for, and for each element, read properties DataCadastro, UsuarioNome and Observacao. This 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>"
              );
      }
  },
  • He has dataType: 'JSON', which leads me to believe that the difficulty lies in working the data received... :/

  • correct would be result.length

  • Corrected. Value!

  • 1

    Make reference to the fact that he has a typo in the code! The source of the problem may be there typo...

  • I already did @Zuul but it’s always good to alert

  • 2

    @Pauloroberto I saw it, but here in Miguel’s answer I was really talking to him to add this info in the answer. And you do the same ;)

  • It’s because I copied the question code that’s also wrong.

  • 1

    It worked for me @Miguelangelo, thank you!

  • Dispose my friend! I am available.

Show 4 more comments

2

You can use an HTML String and play it in your document this way:

          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 were wrong to type result.lenght the correct would be result.length as I used above, if you used result.lenght in your code, there’s definitely been a mistake because of this.

Browser other questions tagged

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