For those who are new to ASP.NET MVC framework but have substantial experience on ASP.NET Web form like yours truly, getting the value of HTML form at client side and binding it to the model at server side is nothing short of absolute magic! This is achieved through Model binder which gets the values from the HTML form and binds them to the model, or the class having getter/setter properties on the server side.
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.
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.
Magical, isn’t it? However, unlike other magicians, I will let you in on the secret.
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.
It is important to note that the value of the name attribute in HTML must be an exact match with the model property or else the binding will not work out.
For this purpose, HTML helpers are quite helpful as they enable us to use the tightly bind model with the HTML helper which generates the HTML with the same name attribute as the model property.
Voila! It’s done! Although this is done via DefaultModelbinder, you can customize the model binder as per your requirement, in case you want to create your own framework. So try it and let me know if it worked as seamlessly for you as it did for me.
Written by Sameer Sharma, .NET Champion at Eternus Solutions
No comments:
Post a Comment