6 The binding model: Retrieving and validating user input

 

This chapter covers

  • Using request values to create binding models
  • Customizing the model-binding process
  • Validating user input using DataAnnotations attributes

In chapter 5 I showed you how to define a route with parameters—perhaps for the day in a calendar or the unique ID for a product page. But say a user requests a given product page—what then? Similarly, what if the request includes data from a form, to change the name of the product, for example? How do you handle that request and access the values the user provided?

In the first half of this chapter, we’ll look at using binding models to retrieve those parameters from the request so that you can use them in your Razor Pages. You’ll see how to take the data posted in the form or in the URL and bind them to C# objects. These objects are passed to your Razor Page handlers as method parameters or are set as properties on your Razor Page PageModel. When your page handler executes, it can use these values to do something useful—return the correct diary entry or change a product’s name, for instance.

6.1 Understanding the models in Razor Pages and MVC

6.2 From request to model: Making the request useful

6.2.1 Binding simple types

6.2.2 Binding complex types

6.2.3 Choosing a binding source

6.3 Handling user input with model validation

6.3.1 The need for validation

6.3.2 Using DataAnnotations attributes for validation

6.3.3 Validating on the server for safety

6.3.4 Validating on the client for user experience

6.4 Organizing your binding models in Razor Pages

Summary