Hi @Blooming Developer ,
Here is a simple demo you can follow:
Model:
public class TestModel
{
public string Name { get; set; }
public int Age { get; set; }
}
View:
@page
@model IndexModel
<button id="addRow" type="button" class="btn btn-info">Add</button>
<form method="post">
<div id="newRow">
<input type="hidden" id="total" value="0" />
</div>
<input type="submit" class="btn btn-primary" value="Post" />
</form>
@section Scripts
{
<script>
$("#addRow").click(function ()
{
var rowCount = parseInt($("#total").val());
rowCount++;
$("#total").val(rowCount);
var html = '';
html += '<div id="inputRow">';
html += '<input type="text" name="[' + (rowCount - 1) + '].Name" />';
html += '<input type="number" name="[' + (rowCount - 1) + '].Age" />';
//add more inputs here...
html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#total").val());
rowCount--;
$("#total").val(rowCount);
$(this).closest('#inputRow').remove();
});
</script>
}
Backend code:
public class IndexModel : PageModel
{
public IActionResult OnGet()
{
return Page();
}
public void OnPost(List<TestModel> model)
{
//do your stuff...
}
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Rena