I am trying to generate a form at run-time. I have ended up with this approach
@using (Html.BeginForm()) {
@foreach (var propertyInfo in typeof(MvcApplication1.Models.LogOnModel).GetProperties()) {
if (propertyInfo.PropertyType == typeof(Boolean)) {
Html.CheckBoxFor(m => new PropertyWrapper<Boolean>(propertyInfo, Model).Property);
}
else if (propertyInfo.PropertyType == typeof(String)) {
Html.TextBoxFor(m => new PropertyWrapper<String>(propertyInfo, Model).Property);
}
...
}
}
With this class to allow the [ElementType]For() methods to work (they need a reference to a property which can't be retrieved using reflection).
public class PropertyWrapper<T> {
private PropertyInfo _propertyInfo;
private Object _instance;
public PropertyWrapper(PropertyInfo propertyInfo, Object instance) {
_propertyInfo = propertyInfo;
_instance = instance;
}
public T Property {
get { return (T)_propertyInfo.GetValue(_instance, null); }
set { _propertyInfo.SetValue(_instance, value, null); }
}
}
I get the following error
System.Reflection.TargetException: Non-static method requires a target.
because instance parameter of PropertyWrapper constructor is null. Am I missing something? Is this even possible?