Chapter 6. The binding model: retrieving and validating user input

 

This chapter covers

  • Using request values to create a binding model
  • 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 a binding model to retrieve those parameters from the request so that you can use them in your action methods. 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 action methods as method parameters so you can do something useful with them—return the correct diary entry or change a product’s name, for instance.

Once your code is executing in an action method, you might be forgiven for thinking that you can happily use the binding model without any further thought. Hold on now, where did that data come from? From a user—you know they can’t be trusted! The second half of the chapter focuses on how to make sure that the values provided by the user are valid and make sense for your app.

6.1. Understanding the M in MVC

6.2. From request to model: making the request useful

6.3. Handling user input with model validation

Summary

sitemap