C# Razor redirect to page with custom route in .NetCore 5

Viewed 213

I want a page for creating/updating a record with a parametric route.

@page "/Clients/Detail/{ClientId?}"
...
<form method="post">
   ...
</form>

If ClientId is null, then use an empty form with for a new record; If ClientId is a number, then load the record and fill the form to update it;

The code behind method is :

public async Task<ActionResult> OnPostAsync([FromServices] ClientsService _service)
    {
        if (ClientId == null)
        {
            CurrentClient.ClientId = Guid.NewGuid().ToString("n");
            while ( await _service.GUIDAlreadyExistsAsync(CurrentClient.ClientId))
            {
                CurrentClient.ClientId = Guid.NewGuid().ToString("n");
            }
            
            await _service.CreateAsync(CurrentClient);
            //todo redirect
            return RedirectToRoute("/Clients/Detail/"+ CurrentClient.ClientId);
        }
        else
        {
            await _service.Update(CurrentClient);
            return RedirectToPage("/Clients/Index");
        }
    }

The record is correctly created but when i'd go back to the /Client/Detail/12345678...AAAA the page not exists.

How can i specify to open the same page now with my generated id?

1 Answers

Try to change

return RedirectToRoute("/Clients/Detail/"+ CurrentClient.ClientId);

to

 return Redirect("/Clients/Detail/" + CurrentClient.ClientId);
Related