简体   繁体   中英

Writing values to Razor Pages fields async

I'm calling an async Task in my Razor Page. I can set the value of my text box in some places in my code but in others not. My comments show where it works and does not. How can I write a value to my textbox in the place my comments say I want to?

<label for="PersonID">PersonID:</label>
<input asp-for="@Model.PersonID" type="text" value="@Model.PersonID" />

public string PersonID { get; set; }

public async void OnGet()
{
    // Do some stuff here
    //Setting PersonID here places the value on my page
        
    await ConnectToPerson();

    //Setting PersonID here DOES NOT place the value on my page
        
}


public async Task ConnectToPerson()
{
    // Do some stuff here
    //Setting PersonID here places the value on my page

    await client.Connect();

    //Setting PersonID here DOES NOT place the value on my page and this is where I want to set it as client will have values returned.

}

This is happening because OnGet and ConnectToPerson return as soon as you hit an async operation. ConnectToPerson returns a Task, which is good, but OnGet does not, so the code calling it has no way to know it had an async operation underway that needed awaiting.

It looks like you can change OnGet to OnGetAsync to perform async operations, returning a Task.

public async Task OnGetAsync()
{
        
    await ConnectToPerson();

    //Set PersonID here
        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM