Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Razor Pages redirect isn't working

I have this OnPost method on my NewGame page:

public IActionResult OnPost()
{
    Name = Request.Form["Name"];
    return RedirectToRoute($"Game/{Name}");
}

And on the Game page I'm redirecting to:

@page "{name}"

However when I submit the NewGame page with a value in the Name field, I get this error:

InvalidOperationException: No route matches the supplied values.

And I'm redirected to Game, not to Game/WhateverNameIEntered. Why is this? I set a breakpoint in my OnPost method and the Name property is getting set from the form field. How can I get the redirect to go to the proper URL?

By the way, isn't the page model Name property supposed to be automatically filled from the field on my form? I wonder why this isn't happening?

like image 727
ekolis Avatar asked Oct 15 '25 16:10

ekolis


1 Answers

First of all you can get the value Name as a parameter in your action:

public IActionResult OnPost(string Name)
{
    :
}

About the redirection you use it the wrong way. I guess Game is a Razor Page in your Pages folder. In that case you can use the following code:

public IActionResult OnPost(string Name)
{
    return RedirectToPage($"/Game", new { Name = Name });
}
like image 165
pitaridis Avatar answered Oct 17 '25 06:10

pitaridis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!