如何在 post 之后添加消息?

How can I add a message after a post?

我有一个带有功能 OnPostAsync() 的身份验证表单,我想在身份验证失败时添加一条错误消息,但我的页面中没有任何消息。

当我从API得到答案时,我使用并设置了一个变量,但是前面的代码不会更新。


Login.cshtml.cs

public string errorMessage { get; set; }

public async void OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return;
    }

    var resp = await _loginService.Connection(user);

    if (resp == null)
    {
        Console.WriteLine("resp null");
        errorMessage = "Incorrect username or password";
        return;
    }
    _cookieService.Set("token", resp);
}

Login.cshtml

<div class="classbody">
    <form class="form-signin" method="post">
        <h1 class="h3 mb-3 font-weight-normal">Connexion</h1>
        <label for="username" class="sr-only">Username</label>
        <input type="text" id="username" class="form-control" placeholder="Username" asp-for="user.Username" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" asp-for="user.Password" required>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Connexion</button>
        <p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p>
        @if (@Model.errorMessage != null)
        {
            <div class="alert alert-danger" role="alert">
                @Model.errorMessage
            </div>
        }
    </form>
</div>

errorMessage = "Incorrect username or password"; 在 await 之后不起作用,如果我把这行放在函数的开头 (OnPostAsync),它运行良好但我在 [=33 之后需要它=]回答。

您应该使用 Task 而不是 void。

WhoKnows 解决了它,现在这是我的代码,它非常有用。

public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var resp = await _loginService.Connection(user);
            if (resp == null)
            {
                Console.WriteLine("resp null");
                errorMessage = "Error";
                return Page();
            }
            return RedirectToPage("/Book");
        }