Home > Net >  How to parse column of table that contain json array to table in asp.net core c#
How to parse column of table that contain json array to table in asp.net core c#

Time:10-14

I have a problem. I have a column in my table that contains a JSON array, and I need to get this value and display it as a table in a cshtml view

I created a method that returns JSON of this value.

public ActionResult GetComposant(String fam)
    {
        var ComposantInfo = ((_context.Fds.Where(e => e.Fam == fam)).ToList()).Select(e => e.Chap2).FirstOrDefault();
        Debug.Write(ComposantInfo);



        return Json(ComposantInfo);
    }

In myjquery script I have:

  $.getJSON("GetComposant", { fam: selectedVal.toString() }, function (result) {
            console.log(result);
            console.log(result.length);


            if (result.length == 0) {
                $('#msg').text("CeTTE FAMILLE n'a pas de FDS , veuillez la creer ");
                $('#msg').css('color', 'red')
                var tr;
                //Append each row to html table

                tr = $('<tr style="background-color: indianred;"/>');

                tr.append("<td contenteditable='true'>"   "</td>");
                tr.append("<td contenteditable='true'>"   "</td>");
                tr.append("<td contenteditable='true'>"   "</td>");
                tr.append("<td contenteditable='true'>"   "</td>");
                tr.append("<td contenteditable='true'>"   "</td>");
                $('table').append(tr);

            }
            else {
                $('#msg').text("FDS existe déja");
                $('#msg').css('color', 'green')
                var tr;
                //Append each row to html table
                for (var i = 0; i < result.length; i  ) {
                    tr = $('<tr/>');
                    tr.append("<td>"   result[i].designe   "</td>");
                    tr.append("<td>"   result[i].ncas   "</td>");
                    tr.append("<td>"   result[i].symbole   "</td>");
                    tr.append("<td>"   result[i].poids   "</td>");
                    tr.append("<td>"   result[i].rphrases   "</td>");
                    $('table').append(tr);
                }
            }



        })

I tried to display the result in my console : it displays: enter image description here

that contains three elements, but when I tried to display the length it display 603

and showed me 603 line of undefined columns.

Where is the problem?

CodePudding user response:

You have to parse the json "string" into an actual js "object" to be able to access it via indexes:

var jsonObj = JSON.parse(result);
// after that you are able to access it's properties
jsonObj [i].designe
  • Related