Search code examples
asp.net-coreblazorblazor-server-side

Blazor OnSubmit does not update Models Values


I have a simple EditForm, however whenever I hit submit the model is not updating and thus not posting the correct infromation.

<EditForm Model="model" OnSubmit="@Submit" FormName="PostCardsTotals">
    <label>Count</label>
    <InputNumber @bind-Value="model.CountOfCards" class="form-control" />
    <br />
    <button type="submit" class="btn btn-primary">Save</button>
</EditForm>

My code looks like this:

@code {
    [Parameter] 
    public int? Id { get; set; }

[SupplyParameterFromForm]
private Metrics model { get; set; } = new Metrics ();

private List<Metrics>? m = new List<Metrics> 

 [Inject]
 public IMetricServcie? metricService { get; set; }

 protected override async Task OnParametersSetAsync()
 {
     if(Id != null) model = await collabriaSerivce.GetCollabriaCardMetricAsync(Id.Value, Selection);
 }

 protected override async Task OnInitializedAsync()
 {
     m = await metricsService.GetMetricsToList();
 }

 async Task Submit()
 {
     // handle the submit
     if (Id != null)
     {
         var res = await service.UpdateMetrics(Id.Value, Selection, model);
     }

 }

}

When I hit submit I can see in my browser tools that the model.CountOfCours has the proper value, however it's not updating server side.

Am I missing something?


Solution

  • OnParametersSetAsync() and OnInitializedAsync() would be calded before Submit(),the value you posted would be overrided by the data you read from db

    Try add a check before you load the data:

    [SupplyParameterFromForm]
    public Metrics? model { get; set; } 
    
    protected override async Task OnParametersSetAsync()
    {
        if (model is null)
        {
            model = //load data from db
        }
        
    }