public class PersonBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // Create a new instance of the model Person person = new Person(); // Use the ModelBindingContext to retrieve the value of a form field ValueProviderResult result = bindingContext.ValueProvider.GetValue("FirstName"); if(result != null) { person.FirstName = result.AttemptedValue; } // Repeat for other fields... return person; } }
public class PersonBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // Create a new instance of the model Person person = new Person(); // Use the ModelBindingContext to retrieve the value of a form field ValueProviderResult result = bindingContext.ValueProvider.GetValue("Age"); if(result != null && int.TryParse(result.AttemptedValue, out int age)) { person.Age = age; } else { // Use the ModelBindingContext to add a custom model state error message bindingContext.ModelState.AddModelError("Age", "Please enter a valid age."); } // Repeat for other fields... return person; } }Package/Library: The ModelBindingContext is part of the System.Web.Mvc assembly, which is included in the Microsoft.AspNet.Mvc NuGet package.