2

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?

2
  • I didn't realize they would be bound automatically! If you make your comment an answer I'll accept. Commented Apr 2, 2012 at 18:30
  • I moved it to an answer. Commented Apr 2, 2012 at 18:31

2 Answers 2

3

Forget about strong typing, the XXXFor helpers and lambda expressions. Once you start the Reflection game you have to play it till the end.

The XXXFor helpers work with very simple expressions such as property accesses.

m => new PropertyWrapper<String>(propertyInfo, Model).Property is far beyond the capabilities of those helpers.

Sign up to request clarification or add additional context in comments.

Comments

1

Why not use the non "for" methods? @Html.CheckBox() for example. Just pass the name of the property to the method, and model binding will still work after postback

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.