The Magical world of Model Binder
In order to fully understand and appreciate the significance of model binding, let us go back in time a bit and recall how things were done in the ‘pre-Model Binding’ era. I used the default register view present in the default MVC project when you create the new project using Visual Studio for this demonstration as shown in the image below.
Now let’s see how it is handled at the server side when you click on the Register button. For this purpose, comment the action register which is using the model binder to get values from the client side to RegisterViewModel in the controller, in order to create the new register action, which accepts the input values as form-collection. The code snippet for the same is given below:
Code snippet with FormCollection:
Once this is done, check debug to see the output obtained in form-collection. As you can see for yourself in the image below, we get the input fields within the form-collection.
However, imagine the situation if your form had hundreds of input fields, or you needed a model within the model. The process would be tedious and time-consuming. You would need to mention the collection[{input field name}] for each input field and there is no intelligence provided by Visual Studio as the field are not tightly bound. Such scenarios are common within banking applications where you need to bind hundreds of fields.
Have no fear when Model binder is there!
I used the following code to perform this otherwise manual, tedious task and could directly access the value from the model itself. Model binder also ensures less errors as compared to the manual process.
Model Binding depends upon the name attribute of the HTML variable which supplies the values. The mapping for the name property is automatic and executes by default.
The HTML in the browser is generated as shown below: