我在一个页面上有2个表单,每个表单都有一个不同的属性。但是,在我的Delete Handler中,modelstate从不在相应表单内的属性中检查验证是否有效...我只想在OnPostAsync Handler上完成 Mail 属性的验证,而不是在“删除”上
[BindProperty]
public StockMailDelivery Mail { get; set; }
[BindProperty]
public IList<int> MailsToDelete { get; set; }
public IList<StockMailDelivery> Mails { get; set; }
#region Handlers
public void OnGet()
{
GetData();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
GetData();
_toastNotification.AddErrorToastMessage("Dados inválidos.");
return Page();
}
_context.StockMailDelivery.Add(Mail);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
_toastNotification.AddErrorToastMessage("Falha ao adicionar.");
_logger.LogError(ex.InnerException.ToString());
GetData();
return Page();
}
_toastNotification.AddSuccessToastMessage("Email adicionado.");
return RedirectToPage("StockMailDelivery");
}
public async Task<IActionResult> OnPostDeleteAsync()
{
if (!ModelState.IsValid)
{
GetData();
_toastNotification.AddErrorToastMessage("Dados inválidos.");
return Page();
}
var mailsToDelete = new List<StockMailDelivery>();
foreach(var item in MailsToDelete)
{
mailsToDelete.Add(new StockMailDelivery(item));
}
_context.StockMailDelivery.RemoveRange(mailsToDelete);
try
{
await _context.SaveChangesAsync();
}
catch(DbUpdateException ex)
{
_toastNotification.AddErrorToastMessage("Falha ao eliminar.");
_logger.LogError(ex.InnerException.ToString());
GetData();
return Page();
}
_toastNotification.AddSuccessToastMessage($"{MailsToDelete.Count()} Email(s) eliminados.");
return RedirectToPage("Mail");
}
html
<form method="post">
<card>
<card-header icon="fas fa-plus" title="Adicionar Recipiente"></card-header>
<card-body>
<label asp-for="Mail.Email"></label>
<input asp-for="Mail.Email" class="form-control" />
</card-body>
<card-footer>
<button class="btn btn-success btn-sm"><i class="fas fa-plus"></i> Adicionar</button>
</card-footer>
</card>
</form>
<form id="delete-mail-form" asp-page-handler="Delete">
<div class="table-responsive">
<table id="tblEmails" class="table table-sm table-bordered" style="width:100%;display:none;">
<thead class="bg-olive">
<tr>
<td>@Html.DisplayNameFor(model => model.Mails[0].Id)</td>
<td>@Html.DisplayNameFor(model => model.Mails[0].Email)</td>
<td></td>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Mails.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(model => Model.Mails[i].Id)
</td>
<td>
@Html.DisplayFor(model => Model.Mails[i].Email)
</td>
<td>
<input type="checkbox" onclick="selectRow(this)" />
<input type="hidden" asp-for="MailsToDelete[i]" value="@Model.Mails[i].Id" />
</td>
</tr>
}
</tbody>
</table>
</div>
</form>