Search code examples
c#asp.net-corerazorrazor-pages

Why is the [BindProperty] required in Razor Pages model binding?


I have the following code in my .cs file:

[BindProperty]
public ApimSubscriptionRoot apimSubscriptions { get; set; }

...which allows me to access the object's properties in my Razor view as:

@Model.apimSubscriptions.someProperty

...however defining it as a field also works in terms of me being able to display the properties of the object in my view:

public ApimSubscriptionRoot apimSubscriptions;

Razor code behind (controller):

public async Task<IActionResult> OnGet() 
{
    (some code...)
    apimSubscriptions = JsonConvert.DeserializeObject<ApimSubscriptionRoot>(contents);
    return Page();
}

Razor page (view):

@page
@model Subscriptions

@{
    ViewData["Title"] = "Your subscriptions";
    ViewData["ActivePage"] = ManageNavPages.Subscriptions;
}

<h4>@ViewData["Title"]</h4>

<div class="row">
    <div class="col-md-12">
        @if (Model.apimSubscriptions.value.Length == 0 || Model.apimSubscriptions == null)

Any explanation as to why would be appreciated.


Solution

  • The BindProperty attribute allows you to access the values entered in the view in OnPost method, i.e. the binding in this case stands for binding from view to model. All public property getters and fields in the model class are accessible in the view since they are considered just object instances that are used by the Razor code.

    The BindProperty attribute is required because a new model object is created when the form is submitted and OnPost is called, and the attribute then directs the Razor Page to set the corresponding values from the form to the matching property.