locked
Json string to table view RRS feed

  • Question

  • User712655675 posted

    Hi there, I am new to MVC 5 and I have gone through javascript which makes me ready for a project. Please don't be upset about this thread as I am trying my best to make it clear. =)

    I would like to make the Json string to display like a table. Here's what I have done:

    Controller.cs

    [HttpPost]
    public JsonResult abc(class.cs parameter) { List<string> tempData = new List<string>(); //for output only ***data input hidden due to my company policy*** using (data db = new data()) { foreach (var x in db) { tempData.Add($"{db.A},{db.B},{db.C}"); } } var obj = tempData; return Json(obj, JsonRequestBehavior.AllowGet);
    }

    View.cshtml

    <p id="testbed"></p> 
    <script>
    $.ajax({ type: "POST", url: '@Url.Action("abc", "Admin")', data: data input, success: function (result) { $('#testbed').html(result); } }, error: function () { alert("Error 404 Data Not Found"); }, }); });
    </script>

    The Json string will return like this

    a,b,c;d,e,f;g,h,i;

    In this case, I want to make a table. The format/layout of Json string might look like .CSV file.

    It looks like I can split into one array by semi-colon, and separate each data into each parameter by comma. I'm just wondering if there is a way to display a table from json string, just like showing .txt file?

    let me know if there is a concern.

    cheers.

    Thursday, July 18, 2019 1:58 AM

Answers

  • User665608656 posted

    Hi yhchoy,

    According to your description, what you want to do is through ajax to read the data from the controller and return to the view to bind the data to the table for display?

    If so,you didn't have to display a table from json string. You can just read the data from json string to display in your view table by jquery.

    I found that you passed parameters from view to controller, so I made a search box for matching table data. You can refer to the following code:

    Index.cshtml

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/Scripts/jquery-3.3.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $.ajax({
                    type: "POST",
                    url: "/JsonData/GetData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var tr;
                        //Append each row to html table
                        for (var i = 0; i < r.length; i++) {
                            tr = $('<tr/>');
                            tr.append("<td>" + r[i].EmplId + "</td>");
                            tr.append("<td>" + r[i].FirstName + "</td>");
                            tr.append("<td>" + r[i].LastName + "</td>");
                            tr.append("<td>" + r[i].EmailAddr + "</td>");
                            $('table').append(tr);
                        }
                    }
                });
    
                $("#Text1").on('input', function () {
                    $.ajax({
                        type: "POST",
                        url: "/JsonData/SearchData",
                        data: '{firstName: "' + $("#Text1").val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (r) {
    //remove all data except first row $("table").find("tr:gt(0)").remove(); var tr; //Append each row to html table for (var i = 0; i < r.length; i++) { tr = $('<tr/>'); tr.append("<td>" + r[i].EmplId + "</td>"); tr.append("<td>" + r[i].FirstName + "</td>"); tr.append("<td>" + r[i].LastName + "</td>"); tr.append("<td>" + r[i].EmailAddr + "</td>"); $('table').append(tr); } } }); }); }); </script> </head> <body> <div> FirstName: <input id="Text1" type="text" /><br /><br /> <table style="border-collapse:collapse;text-align:center" border="1"> <thead> <tr> <th style="width:100px">EmplId</th> <th style="width:150px">FirstName</th> <th style="width:150px">LastName</th> <th style="width:150px">EmailAddr</th> </tr> </thead> <tbody></tbody> </table> </div> </body> </html>

    JsonDataController.cs

            // GET: JsonData
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public JsonResult GetData()
            {
                EntityData entities = new EntityData();
                List<Employee> EmployeeList = (from c in entities.Employees select c).ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }

    [HttpPost]
    public JsonResult SearchData(string firstName)
    {
    EntityData entities = new EntityData();
    List<Employee> EmployeeList = (from c in entities.Employees where c.FirstName.Contains(firstName) select c).ToList();
    return Json(EmployeeList, JsonRequestBehavior.AllowGet);
    }

    The result of this work demo:

    You can also refer to this link:  How To Bind HTML Table Using Json Data In ASP.NET MVC

    Hope this will help you.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 18, 2019 9:55 AM
  • User-474980206 posted

    your sample son does not match what should be return from the ajax call. return the json of a List<string> should return an array of strings. it should look more lie:

    ["a,b,c","d,e,f","g,h,i"]

    a better format would be return an array of arrays 

    [["a","b","c"],["d","e","f"],["g","h","i"]]
    
     var tempData = new List<string[]>();
     using (data db = new data())
     {
        foreach (var x in db)
        {
           tempData.Add(new string[] {db.A, db.B, db.C});
        }
     }
     return Json(tempData,JsonRequestBehavior.AllowGet);
    
    

    then the javascript is:

      success: function (result) {
          var $tbl = $('<table/>');
          for (var r = 0; r < result.lenght; ++r) {
             var $tr = $('<tr/>').appendTo($tbl);
             for (var c = 0; c < result[r].lenght; ++c) {
                $('<td/>').text(result[r][c]).appendTo($tr);
             }
          }
          $('#testbed').html($tbl);
      },
    

    if you want to keep you list comma separated values in a string you just need to do the split:

     success: function (result) {
          var $tbl = $('<table/>');
          for (var r = 0; r < result.lenght; ++r) {
             var $tr = $('<tr/>').appendTo($tbl);
             var cols = result[r].split(',');
             for (var c = 0; c < cols.lenght; ++c) {
                $('<td/>').text(cols[c]).appendTo($tr);
             }
          }
          $('#testbed').html($tbl);
      },

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 18, 2019 4:15 PM

All replies

  • User665608656 posted

    Hi yhchoy,

    According to your description, what you want to do is through ajax to read the data from the controller and return to the view to bind the data to the table for display?

    If so,you didn't have to display a table from json string. You can just read the data from json string to display in your view table by jquery.

    I found that you passed parameters from view to controller, so I made a search box for matching table data. You can refer to the following code:

    Index.cshtml

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/Scripts/jquery-3.3.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $.ajax({
                    type: "POST",
                    url: "/JsonData/GetData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var tr;
                        //Append each row to html table
                        for (var i = 0; i < r.length; i++) {
                            tr = $('<tr/>');
                            tr.append("<td>" + r[i].EmplId + "</td>");
                            tr.append("<td>" + r[i].FirstName + "</td>");
                            tr.append("<td>" + r[i].LastName + "</td>");
                            tr.append("<td>" + r[i].EmailAddr + "</td>");
                            $('table').append(tr);
                        }
                    }
                });
    
                $("#Text1").on('input', function () {
                    $.ajax({
                        type: "POST",
                        url: "/JsonData/SearchData",
                        data: '{firstName: "' + $("#Text1").val() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (r) {
    //remove all data except first row $("table").find("tr:gt(0)").remove(); var tr; //Append each row to html table for (var i = 0; i < r.length; i++) { tr = $('<tr/>'); tr.append("<td>" + r[i].EmplId + "</td>"); tr.append("<td>" + r[i].FirstName + "</td>"); tr.append("<td>" + r[i].LastName + "</td>"); tr.append("<td>" + r[i].EmailAddr + "</td>"); $('table').append(tr); } } }); }); }); </script> </head> <body> <div> FirstName: <input id="Text1" type="text" /><br /><br /> <table style="border-collapse:collapse;text-align:center" border="1"> <thead> <tr> <th style="width:100px">EmplId</th> <th style="width:150px">FirstName</th> <th style="width:150px">LastName</th> <th style="width:150px">EmailAddr</th> </tr> </thead> <tbody></tbody> </table> </div> </body> </html>

    JsonDataController.cs

            // GET: JsonData
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public JsonResult GetData()
            {
                EntityData entities = new EntityData();
                List<Employee> EmployeeList = (from c in entities.Employees select c).ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }

    [HttpPost]
    public JsonResult SearchData(string firstName)
    {
    EntityData entities = new EntityData();
    List<Employee> EmployeeList = (from c in entities.Employees where c.FirstName.Contains(firstName) select c).ToList();
    return Json(EmployeeList, JsonRequestBehavior.AllowGet);
    }

    The result of this work demo:

    You can also refer to this link:  How To Bind HTML Table Using Json Data In ASP.NET MVC

    Hope this will help you.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 18, 2019 9:55 AM
  • User-474980206 posted

    your sample son does not match what should be return from the ajax call. return the json of a List<string> should return an array of strings. it should look more lie:

    ["a,b,c","d,e,f","g,h,i"]

    a better format would be return an array of arrays 

    [["a","b","c"],["d","e","f"],["g","h","i"]]
    
     var tempData = new List<string[]>();
     using (data db = new data())
     {
        foreach (var x in db)
        {
           tempData.Add(new string[] {db.A, db.B, db.C});
        }
     }
     return Json(tempData,JsonRequestBehavior.AllowGet);
    
    

    then the javascript is:

      success: function (result) {
          var $tbl = $('<table/>');
          for (var r = 0; r < result.lenght; ++r) {
             var $tr = $('<tr/>').appendTo($tbl);
             for (var c = 0; c < result[r].lenght; ++c) {
                $('<td/>').text(result[r][c]).appendTo($tr);
             }
          }
          $('#testbed').html($tbl);
      },
    

    if you want to keep you list comma separated values in a string you just need to do the split:

     success: function (result) {
          var $tbl = $('<table/>');
          for (var r = 0; r < result.lenght; ++r) {
             var $tr = $('<tr/>').appendTo($tbl);
             var cols = result[r].split(',');
             for (var c = 0; c < cols.lenght; ++c) {
                $('<td/>').text(cols[c]).appendTo($tr);
             }
          }
          $('#testbed').html($tbl);
      },

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 18, 2019 4:15 PM