Sitecore MVC Custom ID Model Binder
In this post i'll explain how to create a custom Model binder in ASP.net to allow you to pass in a Sitecore ID in your controller action.
For example the controller action below accepts a Sitecore ID, however .net doesn't know how to create the ID class from the form values passed to the action.
This is where custom Model bindings come into play. We are able to create a class that can handle the conversion from the form field value into a Sitecore ID class.
- Firstly we create the custom binder for our type (ID), this inherits from the default binder. We then handle the conversion from string to Sitecore ID.
- The new model binder needs to be added to the collection of Model binders. This means anytime an controller action has a parameters of type ID the custom binder is used to parse the parameter. This code can be added into the Global.asax or done as part of the PreApplicationStart.
- Lastly I have included the unit test I wrote to test the method.