I am trying to delete a row from the table. I get the data when the page is loaded and it must be possible to delete one or more of these data. I managed to delete the row from the UI with javascript, however when I submit the form the propty doesn't get it with what data is left
So I don't know how to tell the backend what data I deleted. I tried to do everything in Javascript, but i can't Modify the modelstate there. thank you for your help
@for (int i=0;i < Model.AuftragsNummern.Count ;i ){
@Html.Hidden("Model.AuftragsNummern.index", i)
@Html.HiddenFor(x => x.AuftragsNummern[i])
<input type="hidden" name="Model.AuftragsNummern.index" value="@Model.AuftragsNummern" />
<tr>
<td>@Html.DisplayFor(x => Model.AuftragsNummern[i])</td>
<td><button asp-page-handler="AuftragDelete" onclick="deleteAuftrage(this)" >delete</button></td>
@{}
</tr>
[BindProperty]
public List<int> AuftragsNummern { get; set; }
function deleteAuftrage(btn){
var row = btn.parentNode.parentNode
row.parentNode.removeChild(row)
}
CodePudding user response:
Model Binding binds the property by name attribute which is in the frontend.
Only input/select/textarea type element with value can be bind to the backend when form submit, but your js just delete the row of @Html.DisplayFor(x => Model.AuftragsNummern[i])
, multiple input elements still exists.
Here is a whole working demo you could follow:
Page
@page
@model IndexModel
<form method="post">
<table>
@for (int i = 0; i < Model.AuftragsNummern.Count; i )
{
<tr>
<td>@Html.DisplayFor(x => Model.AuftragsNummern[i])</td>
<td><button onclick="deleteAuftrage(this)" >delete</button></td>
<input type="hidden" name="AuftragsNummern" value="@Model.AuftragsNummern[i]" />
</tr>
}
</table>
<input type="submit" value="POST" />
</form>
@section Scripts
{
<script>
function deleteAuftrage(btn) {
var row = btn.parentNode.parentNode
row.parentNode.removeChild(row)
}
</script>
}
PageModel
public class IndexModel : PageModel
{
[BindProperty]
public List<int> AuftragsNummern { get; set; }
public void OnGet()
{
AuftragsNummern = new List<int>() { 1, 5, 6, 9, 7 };
}
public void OnPost()
{
}
}