Model binding Post
Model Binding automates the process by which web applications extract
data from HTTP requests and converts it to .NET types, making it easier
to pass information into an input model.
There are two possible frameworks we can use in ASP.NET Core to build web applications – MVC and Razor Pages.
Razor pages are a useful framework to build data-driven websites with a clear separation of concerns.
.cshtml file
Acts
as a "view page", meaning this is where we specify what will be
displayed in our website. Most of the code is in HTML here, but razor
syntax, the syntax used in razor pages, allows us to include executable
C# code. When the razor page is processed, the browser receives HTML
code used to display the page. This file also contains a Model
Directive, which defines the type of model used in the page.
.cshtml.cs file
Nested
behind this there is a .cshtml.cs file, where the Model Directive class
is defined. The .cshtml file will use an instance of this directive
model class to display information.
The .cshtml.cs file, also includes handler methods
These
are methods that are executed when an HTTP request happens. By
convention, they match the HTTP verb used for the request (GET, POST,
PUT, etc) to the name of the method, which always starts with "On".
- When we navigate to a website, the OnGet() handler will be used, because we are performing a GET request
- If there is, for example, a form in the website that we can fill in and then submit, this will trigger the OnPost() handler method, because we are performing a POST request.
In our website, we might often want to reuse code coming from requests in other parts of our model.
For example, if the website contains a form that the user can fill in and submit, we might want to reuse the values submitted somewhere else in the website
When we first navigate to the website, we get a simple form where we can submit our name and surname, and a short sentence is produced.
Capture Post Back
We didn't use model binding here, and yet our form works fine. So, what do we need model binding for?
Model Binding in ASP.NET Core
The goal of model binding is to automate the process of passing information from an HTTP request into an input model.
Lets change our PageModel class
Mode1:
Pass the parameters that we will want to return in the handler method.
These parameters will be of the type of the expected parameters
Mode 2:
The second way of using model binding is to use public properties in
our PageModel. To do this, we need to use the [BindProperty] or
[BindProperties] attribute, which tells our program that we want model
binding to target those specific properties.
Mode 3: The [BindProperties] attribute can be used on a PageModel class to apply model binding to all public properties of the class.