动态调用textboxfor与反思 [英] Dynamically call textboxfor with reflection
问题描述
什么我试图做的最终结果是通过反射物体动态建立一种形式,它的属性。
The end result of what I am trying to do is build a form dynamically by reflecting an object and it's properties.
我已经创建调用TextBoxFor和CheckBoxFor等方法的HtmlHelper,但现在我需要帮助搞清楚如何将它传递给Html.TextBoxFor
I've created HtmlHelper methods that call TextBoxFor and CheckBoxFor and so on, but now I need help figuring out how to properly reflect the property when passing it to Html.TextBoxFor
下面的辅助方法:
public static MvcHtmlString FormTextBox<TModel>(this HtmlHelper<TModel> helper, String id, String property_name, object model, RouteValueDictionary attributes)
{
Type model_type = model.GetType();
return helper.TextBoxFor(model_object => model_type.InvokeMember(property_name, BindingFlags.ExactBinding | BindingFlags.GetProperty, null, model, null));
}
但它打破与此错误code中的回报:
But it breaks on the return with this error code:
模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用。
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
基本上我想采取什么会是这样的:
Basically I want to take what would be this:
@Html.TextBoxFor(model => model.Name)
和把它变成这样:
@FormHelpers.FormTextBox("Name", model)
和有它的输出同样的事情。
And have it output the same thing.
更新
我将重申这一点,因为我在解决问题取得了一些进展。
I will restate this, as I have made some progress in solving the problem.
我创建从防爆pression.PropertyOrField防爆pression创建正是我期待的。不过,我不能让TextBoxFor函数接受它。
I've created an Expression from Expression.PropertyOrField that creates exactly what I am looking for. However I can't get the TextBoxFor function to accept it.
Expression fieldExpr = Expression.PropertyOrField(Expression.Constant(model),property_name);
return helper.TextBoxFor(Expression.Lambda<Func<TModel>>(fieldExpr, null).Compile()());
如何防爆pression正确传递给函数的任何集成开发环境?
Any ides on how to properly pass the Expression to the function?
推荐答案
好吧,我通过使用属性名称和传递的对象的类型建立一个lambda前pression解决了这个问题。我的功能看起来像这样的:
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);
例如:
@{ Name myname = new Name();}
@Html.FormTextBox("first", myname)
字段名建立的左侧(第一)的前pression然后fieldExpr建立与类名和属性名前pression的身体。
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最终看起来是这样的:
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.
这篇关于动态调用textboxfor与反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!