RKh
RKh

Reputation: 14161

Unable to clear Modal when using Async

I am using Blazor framework.

I had an EntryForm which used to generate few text boxes at run-time.

<!-- Input fields -->
@for (var i = 0; i < 6; i++)
{
    var index = i;
    <div class="form-row">
        <div class="col-sm-8" style="float:left">
            <div class="justify-content-center mb-2">
                <input type="text" class="form-control form-control-sm border border-secondary" @bind="myMod.Code[index]" />
            </div>
        </div>
        <div class="col-sm-4" style="float:left">
            <div class="justify-content-center mb-2">
                  <input type="text" class="form-control form-control-sm border border-secondary" @bind="myMod.Weight[index]" @bind:event="oninput" />
            </div>
        </div>
    <div/>
}

There are two buttons after these controls, SAVE and CLOSE.

When user-clicks Save, I have a requirement to confirm from the user. So I added below code:

@code {
    private StudentModel myMod= new StudentModel();
    private void Save()
    {
            bool askUser = ValidateEntry();

            if (askUser)
            {
                Task.Run(async () => await ConfirmSave());
                myMod = new StudentModel();
            }
            else
                Task.Run(async () => await CreateFile());
        }

   async Task ConfirmSave()
    {
        bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", $"Are you sure?");
        if (confirmed)
        {
            await CreateFile();
        }
    }
}

When I was not asking confirmation using ConfirmSave async method, I was able to clear the model by just reinstantiating it. But now even if I do:

myMod = new StudentModel()

it is not clearing the model and therefore after SAVE, the fields retain the previously entered values.

How to clear the model and thereby all fields?

Upvotes: 1

Views: 404

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273244

You don't await the Task.Run(). That means that the rendering that belongs to the ButtonClick is already running before you re-assign myMod.

But the better option is to not use Task.Run() at all.

async Task Save()
{
   ...
   if()
   {
      //Task.Run(async () => await ConfirmSave());
      await ConfirmSave();
      myMod = new StudentModel();
   } 
   else
     //Task.Run(async () => await CreateFile());
     await CreateFile();
}

Upvotes: 1

Related Questions