locked
Should razor page model include fields with annotations for form? RRS feed

  • Question

  • User-81839486 posted

    I can use @model directive only once in razor view so I cant include other view model for form.

    Sunday, August 9, 2020 10:19 PM

Answers

  • User-821857111 posted

    The PageModel is the ViewModel in Razor Pages. The most common pattern is to add properties to the PageModel for each of your form inputs and annotate them as required. Alternatively, you can create a model class for your form inputs and add that as a property to your PageModel. The first option is cleaner, and if you find that decorating a lot of properties with the [BindProperty] attribute is tiresome, you can decorate the PageModel class with [BindProperties] instead.

    https://www.learnrazorpages.com/razor-pages/model-binding#binding-posted-form-values-to-pagemodel-properties

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 10, 2020 7:11 AM

All replies

  • User-474980206 posted

    In razor pages, the @model is the binding model for form fields. It should be used to name and initial form fields, on post back it should be used for validation. Other models can be implemented as page properties.

    Monday, August 10, 2020 1:33 AM
  • User-821857111 posted

    The PageModel is the ViewModel in Razor Pages. The most common pattern is to add properties to the PageModel for each of your form inputs and annotate them as required. Alternatively, you can create a model class for your form inputs and add that as a property to your PageModel. The first option is cleaner, and if you find that decorating a lot of properties with the [BindProperty] attribute is tiresome, you can decorate the PageModel class with [BindProperties] instead.

    https://www.learnrazorpages.com/razor-pages/model-binding#binding-posted-form-values-to-pagemodel-properties

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 10, 2020 7:11 AM