I’m coding a MVC app with ASP .NET 8.0 framework and following code should retrieve a List from my controller to create a 3 columns per n rows table in my view. It run well till the last row:
tableau.appendChild(tbl);
Where I get the error:
Uncaught TypeError: Cannot read properties of null (reading ‘appendChild’)
I didn’t find a way to create my table using the foreach loop so I’m using the for loop with javascript.
@model List<ViewListTable>
<head>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<script type="text/javascript">
function f() {
var myArray = [];
@foreach(var d in Model) {
@: myArray.push("@d.Name");
}
var cptData = myArray.length;
var tableau = document.getElementById('tableau');
var tbl = document.createElement("table");
var x = 0;
for (var i = 0; i < cptData / 3; i++) {
var tr = document.createElement('tr');
for (j = 0; j < 3; j++) {
var td = document.createElement('td');
if (x < cptData) {
var a = document.createElement('a');
var el_span = document.createElement('span');
var linkText = document.createTextNode(myArray[x]);
var tab = myArray[x];
//console.log(tab);
el_span.setAttribute('style', 'color: #07C');
a.setAttribute('href', "'" + tab + "'");
a.setAttribute('class', 'button');
a.title = "Éditer les données de la table:";
a.appendChild(linkText);
el_span.appendChild(a);
td.appendChild(el_span);
};
x += 1;
tr.appendChild(td)
};
tbl.appendChild(tr);
}
tableau.appendChild(tbl);
}
f();
</script>
</head>
<body>
<div id="tableau"></div>
</body>