Search Sreeni's Insights

Filter by content type
technical November 27, 2012 10 min read

How to use filters, model binding and validation? - Part 9

This article explains action filters and the filter pipeline, model binding sources and validation with data annotations and a custom validation attribute in ASP.NET MVC 4.

Share:

How to use filters, model binding and validation? - Part 9

The request pipeline of the MVC has three more parts which decide how much code a controller needs. If we don’t use them, every action starts to read the values from the request and convert them, checks the same security rule, measures its own time, and writes its own try and catch. The actions become long, and the same code is in many of them. In the previous article, we built the views. In this article, we are going to see the filters which give the cross-cutting behavior without changing the actions, the model binding which converts the request to the parameters, and the validation, with our own filter and our own validation attribute.

Student Management System series:

  1. How to structure an ASP.NET MVC application? - Part 1
  2. How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
  3. How does routing work, with custom, nested and area routes? - Part 3
  4. How to model the data with Entity Framework and LINQ? - Part 4
  5. How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
  6. How to build CRUD with Razor views and dependency injection? - Part 6
  7. How to remove the repeated code with a base controller, base service and base repository? - Part 7
  8. How to build the views with layouts, partial views and HTML helpers? - Part 8
  9. How to use filters, model binding and validation? - Part 9 (this article)
  10. How to add registration, login, forgot password, change password, profile and logout? - Part 10
  11. How to build a Web API with ASP.NET MVC 4? - Part 11
  12. How to test the application and keep it clean? - Part 12

TL;DR Summary

  • A filter adds a behavior before or after an action, without changing the action. There are four types, authorization, action, result and exception filters.
  • A filter can be applied to an action, to a controller or to the whole application (a global filter).
  • The model binder fills the action parameters from the route values, the query string and the form, by matching the names.
  • A complex type can be bound from the query string also, so a small class is better than a long list of parameters.
  • The data annotations validate the model on the server, and the same attributes produce the data-val attributes for the client side validation.
  • A custom validation attribute is a class which derives from ValidationAttribute. The server always validates, the client side check is only a convenience.

Common Challenges

The same code in many actions

A timer, a log line, an authorization check or an error handler which is written inside the actions is repeated in all of them, and it hides what the action really does.

Parsing the request by hand

An action which reads Request.QueryString["page"] and converts it with int.Parse must handle the missing and the wrong values. It is a boring code, and it is different in every action.

Validation in many places

When the rules are checked in the controller, again in the service and again in JavaScript, they will differ one day, and the user sees one message on the screen and another one from the server.

Filters

A filter is a class which the MVC calls at a fixed point of the pipeline. The following diagram shows the points.

The filter pipeline around an action method
The filter pipeline around an action method
Filter typeInterfaceRunsExample
AuthorizationIAuthorizationFilterFirst, before everything else[Authorize]
ActionIActionFilterBefore and after the action methodTiming, logging
ResultIResultFilterBefore and after the result is executed (the view is rendered)[OutputCache]
ExceptionIExceptionFilterWhen the action or the filters of the action throw[HandleError]

The built-in filters which we meet often are [Authorize] (only the signed-in users), [HttpPost] (the verb), [ValidateAntiForgeryToken] (the form token, we used it in Part 6), [ChildActionOnly] (Part 8), [OutputCache] (cache the result) and [HandleError] (show the error view for an unhandled exception).

Writing an action filter

Let us write a filter which measures the time of the action method. The easiest way is to derive from the ActionFilterAttribute, which has the virtual methods for the four points,

public class ActionTimerAttribute : ActionFilterAttribute
{
    private const string Key = "ActionTimer";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Items[Key] = Stopwatch.StartNew();
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var timer = filterContext.HttpContext.Items[Key] as Stopwatch;
        if (timer == null || filterContext.IsChildAction)
            return;

        timer.Stop();
        filterContext.Controller.ViewBag.ActionMilliseconds = timer.ElapsedMilliseconds;
    }
}

The filter starts a stopwatch before the action, and stores it in the HttpContext.Items, which lives for one request. After the action, it stops the stopwatch and gives the elapsed time to the view through the ViewBag. The child actions are skipped (IsChildAction), otherwise the child action of the student summary would overwrite the value. The layout prints it in the footer, as we have seen in Part 8, so every screen of this series shows “Action method took … ms” at the bottom right.

Where to apply a filter

A filter can be applied at three levels, and the scope grows with each,

public class StudentsController : Controller
{
    [ActionTimer]                       // one action
    public ActionResult Index(StudentSearchModel search) { ... }
}

[ActionTimer]                           // all the actions of one controller
public class StudentsController : Controller { ... }

// all the actions of the application, in the Application_Start
public static class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ActionTimerAttribute());
    }
}

The sample registers the timer as the global filter, because we want it on every screen. In Part 10 we add the [Authorize] as a global filter, which protects the whole application. In a real application the first global filters are normally [HandleError] and the [Authorize].

Must Be Aware: A filter instance is created once for an attribute and is shared by all the requests, when the attribute is used on a class or a method. Never keep the data of a request in the fields of the filter. We used the HttpContext.Items for this reason.

Model binding

The action parameters are not read by us. The model binder creates them, from the data of the request. It looks for a value with the same name as the parameter in these places, in this order,

Where the model binder reads the values from
Where the model binder reads the values from
  1. The form fields (the POST body).
  2. The route values (/Students/Details/5 gives id = 5).
  3. The query string (?term=Ra&page=2).

The Web API has one more source, the JSON body, and we will see it in Part 11. The matching is by the name and is not case sensitive. Let us see the kinds of the parameters we used in our sample,

// a simple type from the route
public ActionResult Details(int id)

// a simple type which can be missing, the nullable int
public ActionResult Enroll(int id, int? courseId)

// a simple type with a default value
public ActionResult Index(string term, int page = 1)

// a complex type, from the query string
public ActionResult Index(StudentSearchModel search)

// a complex type, from the form
public ActionResult Create(StudentFormModel model)

For a complex type, the binder creates the object with its default constructor and sets each public property from the value with the same name. Our search model is,

public class StudentSearchModel
{
    public StudentSearchModel()
    {
        Page = 1;
    }

    public string Term { get; set; }
    public int Page { get; set; }
}

So the URL /Students?term=Ra&page=2 gives Term = "Ra" and Page = 2, and the URL /Students gives Term = null and Page = 1, because of the constructor. A model like this is better than a long list of the parameters. When we add a filter tomorrow, for example OnlyActive, we add one property and the action signature doesn’t change.

The result of the search with the model binding
The result of the search with the model binding

What if the value can’t be converted, for example ?page=abc? The binder doesn’t throw an exception for a property of a model, it adds an error to the ModelState and leaves the default value. For an action parameter of the type int, which doesn’t have a default, the missing or the wrong value is an exception, and this is the reason why we used the int? for the courseId in Part 8. The other ways to control the binding are,

WayUse
[Bind(Include = "FirstName,LastName")]Allow only some properties to be bound, against the over-posting
FormCollection parameterRead all the form values by the key, when there is no model
TryUpdateModel(student)Bind the request to an existing object, and get false when it is not valid
A custom IModelBinderConvert a special format of the value, which the default binder can’t

In this series we use the view models, which is the simplest way to be safe against the over-posting (Part 6).

Validation

The binder fills the ModelState also. It has the attempted value and the errors of each field. The validation runs during the binding, with the rules which we put on the model with the data annotations,

public class StudentFormModel
{
    [Required, StringLength(50)]
    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Required, EmailAddress]
    public string Email { get; set; }

    [Required, DataType(DataType.Date), MinimumAge(16)]
    [Display(Name = "Date of birth")]
    public DateTime DateOfBirth { get; set; }
}

The action asks ModelState.IsValid, and the view shows the messages with Html.ValidationMessageFor, as we did in Part 6. The same attributes help the client side. Look at the HTML which the TextBoxFor generated for the first name,

<input data-val="true"
       data-val-length="The field First name must be a string with a maximum length of 50."
       data-val-length-max="50"
       data-val-required="The First name field is required."
       id="FirstName" name="FirstName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>

The data-val-* attributes are read by the jquery.validate.unobtrusive.js, which shows the same messages in the browser before the form is posted. It is the unobtrusive validation, there is no JavaScript written by us, and both the server and the client have one set of rules. It is switched on by the two keys of the Web.config, ClientValidationEnabled and UnobtrusiveJavaScriptEnabled, and by the two script files in the Scripts section of the form views.

A custom validation attribute

The built-in attributes don’t have the rule “the student must be at least 16 years old”. We write our own, a class which derives from the ValidationAttribute,

public class MinimumAgeAttribute : ValidationAttribute
{
    private readonly int _years;

    public MinimumAgeAttribute(int years)
    {
        _years = years;
        ErrorMessage = "The student must be at least {0} years old";
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, _years);
    }

    public override bool IsValid(object value)
    {
        if (value is DateTime)
            return ((DateTime)value) <= DateTime.Today.AddYears(-_years);

        return true;
    }
}

The attribute returns true for a missing value. It is the job of the [Required] to complain about it, and the user should see one message and not two. The attribute is used like the built-in ones, [MinimumAge(16)]. The following screen was taken with the JavaScript disabled, so all the messages come from the server,

The server side validation with the custom attribute
The server side validation with the custom attribute

Our attribute doesn’t have the client side rule, so the age is checked only by the server, after the post. To add the client side check, the attribute must implement the IClientValidatable and a JavaScript adapter must be written. It is an extra work, and for a rule like this one, the server side message is acceptable. It is the reason why we say again, the server side validation is the one which counts.

A rule which needs more than one property, for example “the end date must be after the start date”, can’t be written as a property attribute. The model implements the IValidatableObject and its Validate method returns the errors, which are added to the same ModelState.

Testing the validation

The attribute is a plain class, so the unit test is simple,

[Test]
public void MinimumAge_RejectsAStudentWhoIsTooYoung()
{
    var attribute = new MinimumAgeAttribute(16);

    Assert.IsFalse(attribute.IsValid(DateTime.Today.AddYears(-10)));
    Assert.IsTrue(attribute.IsValid(DateTime.Today.AddYears(-20)));
}

Wrap up

In this article, we have looked at the four types of the filters, how to write the action filter and where to apply it, how the model binder reads the values and fills the parameters, the validation with the data annotations and our own attribute, and the data-val attributes for the client side. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to expose the same service as a Web API, and how a screen can use it with jQuery.

Related Posts