Search code examples
c#asp.net-core-2.1razor-pages

Can collections be bound to the page model in Razor Pages?


I have two collections that more or less look like this:

[BindProperty]
public List<MyObject> MyObjects { get; set; } = new List<MyObject>();
[BindProperty]
public List<MyOtherObject> MyOtherObjects { get; set; } = new List<MyOtherObject>();

So they're bounding to the server, but I'm not quite sure how to bind them to the client. Or I'm just doing it wrong. The lists are adding to an HTML table when the page loads, but there's no direct binding:

@foreach (var item in Model.MyObjects)
{
    <tr>
        <td>
            Title
        </td>
        <td>
            @Html.DisplayFor(m => item.Property)
        </td>
    </tr>
}

The issue is that I need to POST to the server to add items to each list at different points. And when I do that, I just return Page();. I'm not redirecting because at this point, nothing is being saved to the database and the form isn't complete.

From my current knowledge, I figure I have two options: redirect and pass the data in the query string or save the data to a cookie and repopulate on every POST.

Both aren't great options. Is there a better way to do this?


Solution

  • Model Binding is designed to work with form values. If you aren't repopulating your collections from persisted data on the server, you need to add form fields for each item to get Model Binding to work. If you are creating a multi-step, wizard-like form, you usually persist unsaved values from each step in hidden fields from one step to the next.