Ich versuche, ein Formular zur Laufzeit zu generieren. Ich habe mit diesem AnsatzASP.NET MVC 3 dynamische Formulargenerierung
@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);
}
...
}
}
Mit dieser Klasse der [ElementType]For()
Methoden zu ermöglichen, am Ende zu arbeiten (sie müssen einen Verweis auf eine Eigenschaft, die nicht mithilfe von Reflektion abgerufen werden kann).
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); }
}
}
bekomme ich folgende Fehler
System.Reflection.TargetException: Non-static method requires a target.
weil instance
Parameter von PropertyWrapper
Konstruktor null ist. Fehle ich etwas? Ist das überhaupt möglich?
Ich wusste nicht, dass sie automatisch gebunden werden würde! Wenn Sie Ihren Kommentar zu einer Antwort machen, akzeptiere ich. –
Ich habe es zu einer Antwort bewegt. –