Dynamically call textboxfor with reflection

巧了我就是萌 提交于 2019-12-01 00:57:53

Ok, I solved this problem by building a lambda expression using the property name and the type of the object being passed in. My function looks like this:

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

Now all I need to do is make sure that my data annotations still work.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!