在运行时创建lambda表达式

时间:2015-02-10 17:24:03

标签: c# lambda expression-trees

如何在运行时在IList

类型的属性上创建lambda表达式

例如,我想要Html.EditorFor(model => model.Properties [i])

public static MvcHtmlString EditorForRepeatGroup<TModel>(this HtmlHelper<TModel> htmlHelper, string PropertyNameToInvoke,int index)
{
    var model = htmlHelper.ViewData.Model;
    var item = Expression.Parameter(model.GetType());

    var format = Expression.Constant(index);

    var prop = Expression.Property(item, PropertyNameToInvoke);
    var args = new Expression[] { format,prop };
    //prop.

    Type type = model.GetType();
    //then lambda
    var lambda =  Expression.Lambda<Func<TModel,string>>(prop,item);


    // I want here:
    //System.Web.Mvc.Html.EditorExtensions.EditorFor(htmlHelper, Model => Model.PropertyNameToInvoke[index]);
    System.Web.Mvc.Html.EditorExtensions.EditorFor(htmlHelper, lambda);

    return null;
}

这肯定失败了。 我是表达的新手,为找到解决方案而筋疲力尽。

编辑:

public class GroupViewModel
{
    public GroupViewModel()
    {
        Properties = new List<PropertyRepeatGroup>();

        for (var i = 0; i < this.GetMaxRepeatGroupValueOf(model => model.Properties); i++)
        {
            Properties.Add(new PropertyRepeatGroup());
        }
    }

    [UIHint("PropertyRepeatGroup")]
    [MaximumRepeatGroups(10)]
    public List<PropertyRepeatGroup> Properties { get; set; }
}

和 我打算用它作为:

 @for (int i = 0; i < 10; i++)
        {

            <div id="tabBody_@i" class="tabBody">
                Property Id : @i

                @Html.EditorForRepeatGroup(property, i);
               //property here is string representation of class property

            </div>
        }

本质上是使上面的视图通用,所以我可以调用

Html.MyPartial(model => model.properties)

Html.MyPartial(otherModel => otherModel.AProperties)

然后是model.properties [x]或otherModel.AProperties [x]

的编辑器模板

0 个答案:

没有答案