Tag Archives: mvc models

Data Annotations

One of the many benefits of separating the concerns of the models, views, and controllers in an MVC application is that each of the three components is able to contain all of the code with which it is concerned. This means, for example, that the view is only concerned with the user interface, and contains only the code that displays a page and data to the user. It doesn’t have any business logic, data access, or any other code unrelated to the user interface.

In the same way, an MVC model is concerned only with data and business logic, nothing else. It interacts with a data store, such as SQL Server, and takes care of all the CRUD operations for maintaining data. In theory, this helps maintain a clean separation of concerns with the other MVC components.

But not everything is always so black and white or neatly partitioned. One issue that would seem like it crosses the component boundary is data validation. On one side, a relational database has certain requirements for data, such as a ProductID that is an integer, and that a company name is a string of one to fifty characters, no more and no less. It may also mandate that every product be assigned to a non-null product category, and that a U.S. Zip code be either five or nine characters in length.

Beyond those data type sort of requirements, you may also have business logic that requires that an email address be of a format that meets the requirements of the Internet, or that no customer can receive more than five orders a year with greater than a 20% discount. All of these data and business logic rules are in place to ensure that stored data is of the highest quality and that the application doesn’t allow any violations of the rules by which the business operates.

But where and how should you define these rules? On one hand, they are the domain of the model because most underlying data stores have requirements that must be met to store data. And because an MVC model is the proper location for business rules, it seems clear that they go in the model as well.

On the other hand, however, it is usually the user interface that needs to take a hand in enforcing the rules and helping the user provide the correct data by displaying error messages when she tries to save data that is missing a field. An input field of type text for the company name might have the max length attribute set to 50, to prevent the user from even entering too many characters in the first place. The user interface clearly has a role to play in data validation.

So where should you implement data validation, in the view or the model? The good news is that with an MVC model there is a clear answer: the model. You add attributes to the properties and classes that implement the model that define the data validation rules, and you can add other data annotations that guide how the view should use the properties of the model. The view can then look at those rules and annotations, and then enforce the rules and appropriately modify how it displays the data to the user. The view’s role in data validation is to take the rules defined in the model—without defining any of its own—and provide a user interface that enforces those rules.

Best of all, since the rules are part of the model, they’ll be in effect no matter where you use the model, across all views and controllers. There is no need to duplicate the rules anywhere in the application. This is an application of the DRY principle of an MVC application: Don’t Repeat Yourself.

James Curtis

This post is an excerpt from the online courseware for our MVC 4.0: Working with Data course written by expert James Curtis.

James Curtis  is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.

ASP.NET MVC Request Validation Protection: AllowHtml Attribute

MVC has always included the same kind of request validation protection that is turned on by default, although you could turn it off by using the ValidateInput attribute with an argument of false. But that has proven to be too blunt a tool for many applications. If you had a single property of a model that could legitimately contain HTML markup—and you protected against crosssite scripting attacks programmatically—you had to turn off request validation for the entire action method.

In MVC 3, there is a better way: the AllowHtml attribute, which you can apply to individual properties of a model. This makes the attribute behave more like other model property-based validation attributes, and gives you very granular control over how request validation is applied. The sample application has a Notes property on the Dog class. If you use the default request validation behavior and add HTML markup to the contents of the Notes field as shown in Figure 22, when you submit the form the application will throw an HttpRequestValidationException as shown in Figure 23. This is a trappable exception that a real application should handle more gracefully than letting the user see a yellow screen of death.

Figure 22. Entering markup in a text field.

Edit Action Method

Figure 23. HttpRequestValidationException as a result of request validation in an MVC application.

If you want to allow HTML markup in the Notes field, simply decorate the property in the Dog model class with the AllowHtml attribute as shown in the following code. With that in place, the application will save the data as regular string data. If you then view the details for the dog, as shown in Figure 24, you’ll see the markup, although the “Irish Setter” part of the text will not appear in bold. Why not?

html markup

Figure 24. HTML markup displayed for a dog in the Notes field.

The good news here is that this view encodes all strings displayed on the page. If you view the page source for the Details view shown in Figure 24, you’ll see the following HTML. This is why the text isn’t bolded and you see the markup.

The Razor view engine encodes all text automatically for you, and if you use the Web forms view engine you can use the special code nugget delimiters <%: %> to encode text. This encoding in the view provides another layer of protection against cross-site scripting attacks, in this case against script and markup that are already infesting the data.

To turn off request validation for the entire model for an action method, you can still use the ValidateInput attribute with a value of false, as shown in the following code. This will allow markup in any of the text fields, as shown in Figure 25. This is not something you want to do lightly!

Edit Action Method

Figure 25. The result of turning off request validation for the entire model in the Edit action method.

Get more training on ASP.NET MVC 2 & 3!