Monday, April 26, 2010

Field Prefix in custom Model Binder

I'm doing some model validation and adding errors to the ModelState at OnModelUpdated in a custom model binder overriding DefaultModelBinder.

However, since the model can be updated either as one of many children in another Model, or on its own, I needed to get the field "prefix" out so that it would highlight the invalid field correctly in the view.

After a lot of unsuccessful searching, it hit upon me to look up the source code for TryUpdateModel to see what it does with the prefix parameter.

Turns out that the ModelName property on ModelBindingContext is the field prefix.

So, I was able to add my model error successfully for both usage cases like this:
string fieldPrefix = (!String.IsNullOrEmpty(bindingContext.ModelName)) ? bindingContext.ModelName + "." : String.Empty; controllerContext.Controller.ViewData.ModelState.AddModelError(fieldPrefix + "PropertyName", "Error Description");

Works for me.

PS: I wanted to use the new DataAnnotation validators for this validation, but since it involves comparing two (or more) fields on the model I was unable to get it working with the correct ModelState error keys. If anyone knows a better way, please let me (and this person on StackOverflow with a similar problem) know!

No comments: