Reputation: 67185
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
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:
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.Upvotes: 4