title: How to create a Model Binder with automatic type cast
body: <p>I need a model binder that cycles all the properties of a type (through reflection) and assign the value to the property. I do it in this way:</p>
  
  <pre><code>public class ModuleModelBinder : DefaultModelBinder
      {
          protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
          {
  
              var m = UtilityModuli.GetAllVociModuli().Where(x =&gt; x.TableName == "Materiali").FirstOrDefault();
  
              var entity = m.Tipo.GetConstructor(new Type[] { }).Invoke(new object[] { });
  
              foreach (var prop in m.Tipo.GetProperties())
              {
                  var propValue = bindingContext.ValueProvider.GetValue("Row."+prop.Name);
                  if (propValue != null &amp;&amp; !string.IsNullOrEmpty(propValue.AttemptedValue))
                  {
                      var value = propValue.AttemptedValue;
                      entity.GetType().GetProperty(prop.Name).SetValue(entity, value);
                  }
              }
  
              bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() =&gt; entity, entity.GetType());
              return entity;
          }
      }
  </code></pre>
  
  <p>But when I try to set value for a int I get an error because I try to enter a string.</p>
  
  <p>What's the best way to convert the data I get from <code>bindingContext.ValueProvider.GetValue ("Row." Prop.Name +)</code> in the right type?</p>