Removing Data Validation from MVC Controllers

Published on May 6, 2015 by Jamie Munro

Problem


You require custom data validation that cannot be accomplished via the built-in data annotation validation attributes - or - your data validation requires access to multiple properties in your model.

Solution


Many times the easy answer is to place the validation inside of your controller. However, I'm a strong believer of placing data validation outside of your controllers and within your data model. This is commonly accomplished by adding data annotation above the properties, such as the [Required] attribute. Another common way is to create your own validation attributes.

This example will use a third way and that is to implement the IValidatableObject interface. This interface defines a Validate function that must be implemented and because it is inside of your data model it has access to all properties within your model.

Read more >

Tags: validation | ASP.NET | mvc5 | ivalidatableobject | validationcontext

Integrating Automapper with an MVC Result Filter

Published on May 4, 2015 by Jamie Munro

Problem


On a variety of actions inside your controllers you call the Automapper NuGet Package to convert from one model to another and you do not want to continue repeating this code each time.

Solution


Applying an MVC result filter to the action can execute the Automapper code after the action has been processed by the MVC framework and before the view is rendered.

Please note this is an excerpt from Chapter 9 of my ASP.NET MVC 5 with Bootstrap and Knockout.js book. In this chapter I provide a brief overview of the 5 different MVC filters and then over the next two chapters provide detail examples of each. The following post is leveraging the example of a Result Filter.

Read more >

Tags: ASP.NET | mvc | automapper | mvc5