Jonathan Wood
Jonathan Wood

Reputation: 67185

Handling multiple forms on the same Razor Page

Has anyone found a trick for handling multiple forms on a Razor Page?

My page has two forms, each with a corresponding model that is decorated with a BindProperty attribute.

[BindProperty]
public TripDetailsUpdateDto UpdateTrip { get; set; }

[BindProperty]
public TripNoteUpdateDto UpdateNote { get; set; }

The problem is that, although either one works fine on its own, having both of them causes ModelState.IsValid to return false. Both models are combined and when one model is submitted, the properties of the other model haven't been set.

Surely I'm not the first to struggle with this. Is there a way to deal with this case without writing manual code to remove the unused items from ModelState?

Upvotes: 3

Views: 2115

Answers (1)

Jonathan Wood
Jonathan Wood

Reputation: 67185

So, as suggested, the problem is that every property of every model decorated with the [BindProperty] is combined into the ModelState.

To resolve the issue, first remove all [BindProperty] attributes.

Then bind to your values with a parameter:

public async Task<IActionResult> OnPostUpdateNoteAsync(int noteId, TripNoteUpdateDto updateNote)
{
    // ...
}

Notes:

  1. You can still have the original model members (in my case, UpdateTrip and UpdateNote). You can still reference them from your markup. This allows your markup to consider validation attributes, and also lets you specify default values.
  2. If your markup references your original model members, your model argument must have the same name in order to match.

Upvotes: 4

Related Questions