I'm building a Blazor web application and having trouble binding form input fields to a model. When the user submits the form, the TrainingInfo.Course property is always null.
Problem:
When I enter text into the "Course Name" field and click the Submit button, the SubmitData() function is called, but TrainingInfo.Course is always null. I've double-checked the @bind-Value binding and TrainingInfo initialization but can’t figure out why the value isn't being updated.
Here’s the relevant code:
TrainingForm.razor
.... <EditForm Model="TrainingInfo" method="post" OnValidSubmit="SubmitData" FormName="trainingForm"> ...<div class="form-floating mb-3"> <InputText @bind-Value="TrainingInfo.Course" id="TrainingInfo.Course" class="form-control" autocomplete="CourseName" aria-required="true" placeholder="CourseName" /> <label for="TrainingInfo.Course" class="form-label">Course Name</label> <ValidationMessage For="() => TrainingInfo.Course" class="text-danger" /> </div> ...<button type="submit" class="w-100 btn btn-lg btn-primary">Submit</button> </EditForm> ...@code { [Parameter] public TrainingInformationModel TrainingInfo { get; set; } = new(); [Parameter] public EventCallback<bool> OnSaveSuccess { get; set; } public async Task SubmitData() { Logger.LogInformation("CourseName: " + TrainingInfo.Course); // This is where the issue is; TrainingInfo.Course is always null } }
Parent Component (TrainingInformationPage.razor)
@page "/TrainingPage" ...<TrainingForm TrainingInfo="@TrainingInfo" OnSaveSuccess="@HandleSaveSuccess" /> ...@code { private TrainingInformationModel TrainingInfo = new(); private void HandleSaveSuccess(bool success) { if (success) { Logger.LogInformation("Training information saved successfully."); } else { Logger.LogError("Training information failed to save."); } } }