ASP.NET Core 2.1 Razor page return Page with model

烂漫一生 提交于 2020-05-15 06:52:25

问题


I am using ASP.NET Core 2.1 for creating an identity server. I use the Asp Identity and I scaffolded the login and register pages.

I have the following page:

[AllowAnonymous]
public class RegisterModel : PageModel
{
 ......
 public string ReturnUrl { get; set; }
 ......
 public void OnGet(string returnUrl = null)
 {
     ReturnUrl = returnUrl;
 }
 public async Task<IActionResult> OnPostAsync(string returnUrl = null)
 {
     returnUrl = returnUrl ?? Url.Content("~/");
     if (ModelState.IsValid)
     {
         return LocalRedirect(returnUrl);
     }

     return Page();
}

The cshtml contains:

@page
@model RegisterModel
......
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
......

Behaviour: I land on the page on this link: https://localhost:5028/Identity/Account/Register?returnUrl=testlink , so the ReturnUrl gets set to "testlink" in the OnGet() and is passed on to the form.

  1. Correct: If I create a user with no validation errors (ModelState is valid), then LocalRedirect(returnurl) gets called with "testlink".
  2. Wrong: If I create a user with validation errors (ModelState is invalid), then return Page() gets called. The issue is that in this case, the page is generated with empty model (@Model.ReturnUrl is null). The user sees the validation errors in the form, corrects them, but when he submits the form, he won't get redirected to "testlink" because it was lost.

My question: With what do I replace "return Page();" so that I can correct behaviour described on case 2? I tried "return LocalRedirect("/Identity/Account/Register?returnUrl=" + returnUrl)", but that refreshes the page (clears user input and doesn't show validation error messages).

Thank you!


回答1:


Set the ReturnUrl property on POST so it is available when the page reloads.

public IActionResult OnPost(string returnUrl = null) {
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid) {
        return LocalRedirect(returnUrl);
    }
    //...if we get this far something went wrong.
    //reset properties on model so they appear when page reloads
    ReturnUrl = returnUrl;
    return Page();
}


来源:https://stackoverflow.com/questions/52693364/asp-net-core-2-1-razor-page-return-page-with-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!