简体   繁体   English

将值写入 Razor 页面字段异步

[英]Writing values to Razor Pages fields async

I'm calling an async Task in my Razor Page.我在我的 Razor 页面中调用异步任务。 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.发生这种情况是因为 OnGet 和 ConnectToPerson 在您执行异步操作后立即返回。 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. ConnectToPerson 返回一个 Task,这很好,但 OnGet 没有,因此调用它的代码无法知道它正在进行需要等待的异步操作。

It looks like you can change OnGet to OnGetAsync to perform async operations, returning a Task. 看起来您可以将 OnGet 更改为 OnGetAsync 以执行异步操作,并返回一个任务。

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

    //Set PersonID here
        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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