Idea behind Model Binder
As defined in MSDN: A model binder in MVC provides a simple way to map posted form values to a .NET Framework type and pass the type to an action method as a parameter. Binders also give you control over the deserialization of types that are passed to action methods. Model binders are like type converters, because they can convert HTTP requests into objects that are passed to an action method. However, they also have information about the current controller context.
A model binder lets you associate a class that implements the IModelBinder interface using an action-method parameter or using a type. The IModelBinder interface contains a GetValue method that the framework calls in order to retrieve the value of a specified parameter or type. The DefaultModelBinder class works with most .NET Framework types, including arrays and IList, ICollection, and IDictionary objects.
If 'ModelState.IsValid' is false means your post data are not following the patterns which is defined in model class properties and add error message into 'ModelState.AddModelError' dictionary object and populate errors in respective view.
Above mechanism will happen automatically during runtime using default model binder when controller is called from HTTP request .
Model Binder in Test Framework
Model Binder runs automatically during runtime in ASP.NET MVC framework but not in Test Framework then how we can do model validation in Test Framework. Let us create both project in one solution as below:
Model Binder runs automatically during runtime in ASP.NET MVC framework but not in Test Framework then how we can do model validation in Test Framework. Let us create both project in one solution as below:
Below is the model class decorated with email validation.
I have created Action method as 'Post' and passing 'Name' and 'Email' properties to 'Register' Model class.
Index View with 'Register View' as Action Link as below:
After clicking on Action link and post model properties as below
'IsValid' boolean property is true because i am passing email id in correct format as below:
Here I am passing email id as wrong format so 'IsValid' property is false as below:
Manoj KallaPosted Jan 30, 2016, 11:38 AM
Nice one
Mohammed IbrahimPosted Jan 25, 2016, 4:42 AM
nice
Raja TPosted Jan 24, 2016, 11:09 PM
Nice, Thank you for sharing..
Humayun Kabir MamunPosted Jan 24, 2016, 10:47 PM
Nice...
Jaco ZwartsPosted Jan 24, 2016, 2:17 PM
Really good article well done thank you for sharing!
Santhakumar MunuswamyPosted Jan 24, 2016, 10:54 AM
Thanks for nice share
Gowtham KPosted Jan 24, 2016, 6:16 AM
Good Share