Validation
Source: http://www.markeverard.com/blog/2011/07/18/creating-a-custom-modelbinder-allowing-validation-of-injected-composite-models/
Custom ModelBinders don’t seem to run validation on the newly created model automatically, so while you may add validation attributes to your model you need to add in some extra code to force validation to occur.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()); | |
ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controllerContext); | |
foreach (ModelValidationResult result in compositeValidator.Validate(null)) | |
bindingContext.ModelState.AddModelError(ValidationPropertyName, result.Message); |
Entities
Source: http://lostechies.com/jimmybogard/2011/07/07/intelligent-model-binding-with-model-binder-providers/
An interesting technique I’ve seen used is using modelbinding to automatically load an entity based on the id passed in. So your actions ask for an entity instead of an Id.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult View(User entity) { | |
UserEditModel model = //change entity into a edit model | |
return View(model); | |
} |
This idea could be extended to work on list pages by creating a filter criteria from all route values (page, sort, search)
Dependency Injecting Model Binders
Source: http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Model-Binders.aspx
Out of the box you can’t use dependency injection with ModelBinders, you can however pass objects in when you create them at registration time. If your ModelBinders only take singletons then that approach works, otherwise create a fairly basic modelbinder that takes your kernel as a parameter and when binding method is called use the kernel to create your real model binder complete with full dependency injection.
DateTimes
For a recent projet I didn’t want to use a javascript datetime picker as it was meant to be used on a horrible android tablet, but I still wanted something a bit friendlier than a textbox. I chose to split dates into day/month/year fields, which would be a lot of effort to do to every date manually.
Instead I made an Editor Template for DateTimes which outputs 3 fields, and a custom ModelBinder that when binding dates looks for 3 fields instead of just 1.