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:

public class ModuleModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {

            var m = UtilityModuli.GetAllVociModuli().Where(x => 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 && !string.IsNullOrEmpty(propValue.AttemptedValue))
                {
                    var value = propValue.AttemptedValue;
                    entity.GetType().GetProperty(prop.Name).SetValue(entity, value);
                }
            }

            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => entity, entity.GetType());
            return entity;
        }
    }

But when I try to set value for a int I get an error because I try to enter a string.

What's the best way to convert the data I get from bindingContext.ValueProvider.GetValue ("Row." Prop.Name +) in the right type?

Related posts

Recent Viewed