In which order is model binding and validation done in ASP.NET MVC 2?
- by Simon Bartlett
I am using ASP.NET MVC 2, and am using a view-model per view approach. I am also using Automapper to map properties from my domain-model to the view-model.
Take this example view-model (with Required data annotation attributes for validation purposes):
public class BlogPost_ViewModel
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Text { get; set; }
}
In the post editor view I am using a rich text editor (CKeditor). Because CKeditor is a HTML editor, I ideally need CKeditor to HTMLencode the user's input when the form is submitted, so that ASP.NET's input validation does not complain. This is not a problem as CKeditor has this functionality built in, however I need CKeditor's output decoded before mapping back to the domain object (via Automapper).
I am wanting to add a new property (to the view-model above) to solve this, as follows:
public string HTMLEncodedText {
get { return HTMLEncode(Text); }
set { Text = HTMLDecode(value); }
}
I can then bind this property to CKeditor in the view, but still use Automapper to map the 'Text' property in the controller - all without having to turn input-validation off.
My question is: do you know how the model binding and validation process in ASP.NET MVC 2 works? Are all model properties binded before validation is carried out? Or is each individual property get validated when it is being set. I think ideally for my idea to work, all properties need to be set before the model is validated.