I am trying to create a simple counter for a dynamic table I am creating. Essentially, every time I add a row to the table I want the counter to increase by 1. I'm trying to avoid adding some arbitrary property to the model if I can avoid it but I am really scratching my head at how to get this to work.
My table starts with 2 rows and is model-bound to a list. The intent here is to allow every new row after that to be given a new index so it can be submitted with the form and create the list as I go (one submit action further down in the view, the addRow() function is called with a button that does not submit the form)
Essentially here's what I have in my view
@model AddUsers
@{
ViewData["Title"] = "Add Users";
var Counter = 2;
}
@section Scripts{
<script>
function addCount() {
var count = @Counter;
console.log('count: ' + count + 'counter: ' + '@Counter');
count = count + 1;
@Counter = count;
console.log('count: ' + count + 'counter: ' + '@Counter');
}
</script>
<script>
function addRow() {
var counter = @Counter;
var table = document.getElementById("AddUsersTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text" asp-for="Users[' + counter + '].FirstName"/><br /><span asp-validation-for="Users[' + counter + '].FirstName class="text-danger"></span>';
var cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text" />';
var cell3 = row.insertCell(2);
cell3.innerHTML = '<input type="text" />';
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="text" />';
addCount();
}
</script>
}
When I debug this and view the log and elements in the browser, I see the following.
I am clearly missing something crucial as none of this is working as expected.
What should have been a simple counter is turning out to be a bigger headache than I anticipated. I tried some of the answers and comments from here as well as my own tinkering to no avail.


