We have two buttons inside of an Editform. They do a bit of different things. But we want the Data annotation validation to work on both button click. The first button is easy, it triggers the OnValidSubmit. But the second button, although it triggers page validation, still writes to console.
Below is the class used:
using System.ComponentModel.DataAnnotations;
namespace MyApp.Client.Models
{
public class TestModel
{
[Required]
public string MyName { get; set; }
}
}
Below is the razor component which includes two buttons and one inputtext field:
@page "/test"
<h3>test</h3>
<EditForm Model="model" OnValidSubmit="PostAsync" class="mt-5">
<DataAnnotationsValidator></DataAnnotationsValidator>
<ValidationSummary></ValidationSummary>
<div class="row w-100">
<div class="col-md-6">
<div class="float-lg-right row">
<div class="col-6 text-center">
<button type="submit" class="btn btn-success text-black w-100">Save</button>
</div>
<div class="col-6 text-center">
<button type="submit" class="btn btn-success text-black w-100" @onclick="(async ()=>await SaveAndGoToListAsync())">Save & Go To List</button>
</div>
</div>
</div>
<div class="col-md-3 mb-3">
<label for="MyName" class="col-form-label">My Name:</label>
<InputText id="MyName" class="form-control" @bind-Value="model.MyName"></InputText>
<ValidationMessage For="@(()=>model.MyName)"></ValidationMessage>
</div>
</div>
</EditForm>
@code {
private TestModel model;
public Test()
{
model = new();
}
private void PostAsync()
{
Console.WriteLine("PostAsync");
}
private async Task SaveAndGoToListAsync()
{
Console.WriteLine("SaveAndGoToListAsync");
}
}