Razor Page: RedirectToPage with Parameters
Asked Answered
D

2

16

I have a razor page which displays company and list of staff:

@page "/admin/companies/editor/{id}"
@model EditorModel
@{
}

<h1>admin . companies . editor</h1>


<h4>Id = @Model.Id</h4>
<h4>Name = @Model.OrgStructure.Organisation.Name</h4>
<h4>Staff Count = @Model.OrgStructure.Staff.Count</h4>

<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
    </tr>
    @if (Model.OrgStructure.Staff.Any())
    {
        foreach (Staff s in Model.OrgStructure.Staff)
        {
            <tr>
                <td>@s.Id</td>
                <td>@s.Username</td>
            </tr>
        }
    }
    else
    {
        <tr>
            <td colspan="2">No Staff</td>
        </tr>
    }
</table>
<a class="btn btn-primary" asp-page="/admin/companies/staff/create" asp-route-orgId="@Model.OrgStructure.Organisation.Id">Create Staff</a>


@functions {
    public class EditorModel : PageModel
    {

        public string Id { get; set; }

        public OrganisationStructure OrgStructure { get; set; }

        public void OnGet(string id)
        {
            Id = id;
            using (DirectoryApp app = ServicesFactory.MakeDirectoryService())
            {
                OrgStructure = app.GetOrganisationStructureAsync(new Guid(id)).Result;
            }
        }
    }
}

When I click:

    <a class="btn btn-primary" asp-page="/admin/companies/staff/create" asp-route-orgId="@Model.OrgStructure.Organisation.Id">Create Staff</a>

It takes me to my staff creation page:

@page "/admin/companies/staff/create/{orgId}"
@model CreateModel
@{
}

<h1>admin . companies . staff . create</h1>

<h3>OrganisationId = @Model.OrganisationId</h3>

<form method="post">
    <input name="OrgId" value="@Model.OrganisationId" />
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label>User Name</label>
        <input name="UserName" class="form-control" value="@Model.UserName" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
    <a class="btn btn-secondary" asp-page="/admin/companies/editor" asp-route-id="@Model.OrganisationId">Back</a>
</form>

@functions {
    public class CreateModel : PageModel
    {
        [BindProperty]
        [Required]
        public string UserName { get; set; }

        public Guid OrganisationId { get; set; }

        public void OnGet(string orgId)
        {
            OrganisationId = new Guid(orgId);
        }

        public async Task<IActionResult> OnPostAsync(string userName, string orgId)
        {
            if (ModelState.IsValid)
            {
                using (DirectoryApp app = ServicesFactory.MakeDirectoryService())
                {
                    await app.AddStaffToOrganisationAsync(
                        new Guid(orgId),
                        new Staff()
                        {
                            Username = userName
                        });
                    return RedirectToPage("/admin/companies/editor/" + orgId.ToString());
                }
            }
            return Page();
        }
    }
}

I have 2 questions:

  1. If I click Submit and have a Model error then I get the error message but the fields which are using @Model.OrganisationId are blanked out. I guess that when OrganisationId is set in the OnGet() method, this is lost after a post. Does this mean I'd need to repopulate my CreateModel.OrganisationId in the OnPostAsync() method?

  2. If I am successful the line:

return RedirectToPage("/admin/companies/editor/" + orgId.ToString());

should take me back to the original screen viewing the company with the newly added staff member. However, I am getting an error:

An unhandled exception occurred while processing the request. InvalidOperationException: No page named '/admin/companies/editor/473be1aa-7d62-4964-b744-b34e0489d7ad' matches the supplied values.

But, if I copy and paste the "/admin/companies/editor/473b..." into the address bar in the browser after "localhost:12345" then the page opens no problem.

What am I doing wrong?

UPDATE

I need to replace:

return RedirectToPage("/admin/companies/editor/" + orgId.ToString());

with

return RedirectToPage("/admin/companies/editor", new { id = orgId.ToString() });
Dolorisdolorita answered 7/12, 2020 at 13:38 Comment(0)
D
9

If I click Submit and have a Model error then I get the error message but the fields which are using @Model.OrganisationId are blanked out. I guess that when OrganisationId is set in the OnGet() method, this is lost after a post. Does this mean I'd need to repopulate my CreateModel.OrganisationId in the OnPostAsync() method?

The answer to this was:

  1. Instead of declaring arguments in the OnPostAsync method, I should use the properties in the CreateModel itself (with binding).
  2. Use [BindProperty] on OrganisationId property in CreateModel.
  3. On the input control, change name of OrgId field to OrganisationId.

So:

<input name="OrgId" value="@Model.OrganisationId" />

Changes to:

<input name="OrganisationId" value="@Model.OrganisationId" />

AND

    public async Task<IActionResult> OnPostAsync(string userName, string orgId)
    {
        if (ModelState.IsValid)
        {
            using (DirectoryApp app = ServicesFactory.MakeDirectoryService())
            {
                await app.AddStaffToOrganisationAsync(
                    new Guid(orgId),
                    new Staff()
                    {
                        Username = userName
                    });
                return RedirectToPage("/admin/companies/editor/" + orgId.ToString());
            }
        }
        return Page();
    }

Changes to:

    public async Task<IActionResult> OnPostAsync()
    {
        if (ModelState.IsValid)
        {
            using (DirectoryApp app = ServicesFactory.MakeDirectoryService())
            {
                await app.AddStaffToOrganisationAsync(
                    OrganisationId,
                    new Staff()
                    {
                        Username = this.UserName
                    });
                return RedirectToPage("/admin/companies/editor", new { id = OrganisationId.ToString() });
            }
        }
        return Page();
    }

AND

    [BindProperty]
    [Required]
    public string UserName { get; set; }

    public Guid OrganisationId { get; set; }

Changes to

    [BindProperty]
    [Required]
    public string UserName { get; set; }

    [BindProperty]
    public Guid OrganisationId { get; set; }

Using the above:

  1. On a Post that fails Model validation, the properties persist on the UI after

    return Page();

  2. The Redirect to page works now that I have move the parameter to the second argument as an anonymous object, instead of concatenating a string as a query parameter.

Dolorisdolorita answered 7/12, 2020 at 15:24 Comment(0)
J
2

RedirectToPage("/admin/companies/editor", new { id = OrganisationId.ToString() }) is correct

If you need to pass a list as parameters for RedirectToPage you can do it like this:

return RedirectToPage("./Index", new { MigrationStatus = new List<int>() { (int)MigrationStatus.AwaitingStart, (int)MigrationStatus.InProgress } });

It will create a URL like this:

https://localhost:123/Migrations?MigrationStatus=3&MigrationStatus=4

Justiciable answered 17/2, 2023 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.