In an ASP.NET Core Razor Pages POST handler, when do you return Page() and when RedirectToPage(), and what does each one do?
answer
- PageResult renders in this request
- OnGet does not run again
- RedirectToPageResult sends 302
- ./Index, ../Index, /Index
- unknown page throws, no empty Location
basics
~20 sPage() renders the current page in the same request, keeping posted values and ModelState errors, which suits a failed validation; OnGet does not run. RedirectToPage() sends a 302 to a page's URL so the browser issues a GET, which suits success.
solid answer
~40 s`Page()` returns a `PageResult`: the page's `.cshtml` renders now, in the POST request, from the current `PageModel` state, so `[BindProperty]` values and `ModelState` errors appear in the form. It does **not** call `OnGet`, so anything only `OnGet` loaded, such as the dentist list for a `<select>`, is empty unless the POST handler loads it again. `RedirectToPage("./Index")` returns a `RedirectToPageResult`: Razor Pages generates the target page's URL (with route values, `RedirectToPage("./Details", new { id })`) and sends **302 Found**; the browser then issues a GET. `RedirectToPagePermanent` sends 301 and `RedirectToPagePreserveMethod` 307. Page names are relative to the current page's folder unless they start with `/`, and a name that matches no page throws `InvalidOperationException`. Return `Page()` when the user must fix input; redirect after the change succeeds.
code
csharp · 22 linespublic class BookModel(IAppointmentService appointments) : PageModel
{
[BindProperty] public BookingInput Input { get; set; } = new();
public SelectList Dentists { get; private set; } = default!;
public async Task OnGetAsync() => Dentists = await LoadDentistsAsync();
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
Dentists = await LoadDentistsAsync(); // OnGet is not re-run
return Page(); // 200, form with errors
}
var id = await appointments.BookAsync(Input);
return RedirectToPage("./Details", new { id }); // 302
}
private async Task<SelectList> LoadDentistsAsync() =>
new(await appointments.GetDentistsAsync(), "Id", "Name");
}go deeper
Recall that Page() shows the current page again and RedirectToPage() sends the browser to another page with a redirect.
Explain PageResult versus RedirectToPageResult, why OnGet does not run on Page(), the status codes, and relative page names.
Prevent the empty-dropdown bug, choose 302, 301 or 307 deliberately, and keep success paths redirecting so refreshes cannot repeat a booking.
Standardise handler result patterns across a Razor Pages codebase so error display, redirects and flash messages behave the same everywhere.
## Two results, two requests A Razor Pages handler ends by returning an `IActionResult`. After a form POST, two are used most: | | `Page()` | `RedirectToPage(...)` | |---|---|---| | Result type | `PageResult` | `RedirectToPageResult` | | What the browser receives | 200 with the page's HTML | 302 with a `Location` header | | Requests involved | the POST only | the POST plus a new GET | | `OnGet` runs? | no | yes, on the target page's GET | | Posted values and `ModelState` | shown in the form | gone; the GET starts fresh | | Typical use | validation failed, show errors | the change succeeded | A handler that returns `void` or `Task`, or `null`, gets an implicit `Page()`. ## Page(): render now, with what you have On the dentist's booking page: ```csharp public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { Dentists = await LoadDentistsAsync(); // OnGet does not run for this POST return Page(); } var id = await appointments.BookAsync(Input); return RedirectToPage("./Details", new { id }); } ``` `Page()` renders `Book.cshtml` against the same `BookModel` instance. Everything the POST bound is still there: `Input` holds what the patient typed, and `asp-for` reads attempted values from `ModelState`, so the form comes back filled with validation messages. What is **not** there is anything only `OnGetAsync` sets. Razor Pages runs exactly one handler per request, and for a POST that is the POST handler. A `<select asp-items="Model.Dentists">` whose list was loaded in `OnGetAsync` throws or renders empty after a failed POST. The fixes: - load shared display data in a private method both handlers call; - or load it in the page filter override `OnPageHandlerExecutionAsync` for every request. ## RedirectToPage(): send the browser elsewhere `RedirectToPage` builds the target page's URL through routing and writes it to the `Location` header: - `RedirectToPage("./Index")` sends **302 Found** through `Response.Redirect`; - `RedirectToPagePermanent(...)` sends **301**; - `RedirectToPagePreserveMethod(...)` sends **307**, and `RedirectToPagePermanentPreserveMethod(...)` **308**, which tell the browser to repeat the same method and body. Route values go in an anonymous object, `RedirectToPage("./Details", new { id })`, and fill the target's `@page "{id:int}"` segment. The handler name can be passed too, `RedirectToPage("./Details", "Slots", new { id })`. If the name matches no page, the redirect does not quietly send an empty `Location`: executing the result throws `InvalidOperationException` ("No page named ... matches the supplied values"). ## Relative page names Names resolve against the current page's folder. From `Pages/Appointments/Book.cshtml`: 1. `RedirectToPage("./Index")` and `RedirectToPage("Index")` go to `Pages/Appointments/Index`; 2. `RedirectToPage("../Index")` goes to `Pages/Index`; 3. `RedirectToPage("/Index")` goes to `Pages/Index`, from anywhere. Relative names keep working when a folder is renamed; root-relative names survive moving the calling page. ## Other results a handler can return `PageModel` has helpers for most outcomes besides the two above: | Helper | Result | Typical use | |---|---|---| | `NotFound()` | 404 | the appointment id does not exist | | `Forbid()` | a forbid through the authentication scheme (403, or the cookie scheme's access-denied page) | the user may not change this appointment | | `Partial("_Slots", slots)` | a partial view's HTML | a script refreshing one fragment | | `new JsonResult(slots)` | JSON | a named GET handler feeding a script | | `Redirect(url)` / `LocalRedirect(url)` | 302 to a URL | a return URL; `LocalRedirect` refuses external URLs | Each is an `IActionResult`, so the handler's return type is `IActionResult` or `Task<IActionResult>` whenever more than one outcome is possible. ## Choosing between them - Validation failed or the operation was refused for a reason the user can fix: `Page()`, after reloading display data. - The change succeeded: redirect, so a browser refresh re-runs a harmless GET instead of re-posting the booking. - The record is gone: `NotFound()`. A one-off message on the next page ("Appointment booked") travels in `TempData` across the redirect, which is a session-state topic.
- After a failed POST the page throws a NullReferenceException in the dentist dropdown. Why?`return Page()` renders the page in the POST request, and only the POST handler ran. The `Dentists` list was set in `OnGetAsync`, which never executed for this request, so `asp-items="Model.Dentists"` received `null`. Reload the list in the POST path before returning `Page()`, ideally through a helper both handlers call.
- When would you use RedirectToPagePreserveMethod instead of RedirectToPage?When the client must repeat the same request method and body at the new URL, for example forwarding a POST to a page that moved. It sends 307 (or 308 for the permanent variant), where `RedirectToPage` sends 302 and the browser follows with a GET. After a successful form POST you want the GET, so plain `RedirectToPage` is the normal choice.
- return Page() runs OnGet again before rendering
- return Page() sends a redirect back to the same page
- RedirectToPage keeps ModelState errors for the next request
- RedirectToPage to a misspelled page sends an empty Location header
- RedirectToPage("Index") always means Pages/Index.cshtml at the root