The end result of what I am trying to do is build a form dynamically by reflecting an object and it\'s properties.
I\'ve created HtmlHelper methods that call TextBo
To get a property using reflection, use code like this:
var prop = model_type.GetProperty(property_name);
//then in your loop:
prop.GetValue(model, null)
Or if you're only going to get the property from one object, make it one line:
model_type.GetProperty(property_name).GetValue(model, null);
Ok, I solved this problem by building a lambda expression using the property name and the type of the object being passed in using the library System.Linq.Expressions
.
ParameterExpression fieldName = Expression.Parameter(typeof(object), property_name);
Expression fieldExpr = Expression.PropertyOrField(Expression.Constant(model), property_name);
Expression<Func<TModel, object>> exp = Expression.Lambda<Func<TModel, object>>(fieldExpr, fieldName);
return helper.TextBoxFor(exp);
Example:
@{ Name myname = new Name();}
@Html.FormTextBox("first", myname)
fieldName builds an expression for the left hand side (first) and then fieldExpr builds the body of the expression with the class name and property name.
exp ends up looking like this:
first => value(DynamicForm.Models.Name).first