HTMLHelper,生成属性"Expression <Func <TModel,TValue >> expression"的参数

Ane*_*ook 6 reflection asp.net-mvc html-helper

我正在为编辑器编写HTML Helper.我们的想法是使用属性AutoGenerateField从Model获取属性并构建一个表,其中每行包含一个字段的名称(也来自属性)和一个包含字段实际值的TextBox或CheckBox.

我有HTMLHelper的问题.由于我将整个模型发送给助手而不是一个值,因此我不能使用TextBoxFor等方法,因为它们需要参数,例如

"Expression<Func<TModel, TValue>> expression".
Run Code Online (Sandbox Code Playgroud)

我正在使用反射,我尝试发送属性,但VisualStudio认为这是不正确的用法.

下面是我的HtmlHelper的简化方法:

public static MvcHtmlString GenerateEditor<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    var model = htmlHelper.ViewData.Model;
    var result = String.Empty;

    //generating container, etc ...

    foreach (var property in model.GetType().GetProperties())
    {
        var attr = property.GetCustomAttributes(typeof (DisplayAttribute), true).FirstOrDefault(); 
        if (attr == null) continue;
        var autoGenerate = ((DisplayAttribute)attr).AutoGenerateField;
        if(autoGenerate)
        {
           //here I'm building the html string 
           //My problem is in the line below:
           var r = htmlHelper.TextBoxFor(property); 
        }
    }
    return MvcHtmlString.Create(result);
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

gid*_*eon 2

只使用非 lambda 重载怎么样?:InputExtensions.TextBox()

if(autoGenerate)
{
   //here I'm building the html string 
   //My problem is in the line below:
   var r = htmlHelper.TextBox(property.Name); 
}
//not sure what you do with r from here...
Run Code Online (Sandbox Code Playgroud)

如果我没有记错的话,name即使您使用函数的 lambda 版本,表单元素的属性也会设置为属性名称,因此这应该执行相同的操作。

我将尝试验证 lambda 函数的作用,您也许可以做同样的事情,因为您有 lambda 函数TModel


更新

快速查看InputExtensions.cs源代码内部的内容, TextBoxFor 调用最终调用InputHelper(),最终调用ExpressionHelper.csExpressionHelper.GetExpressionText(LambdaExpression expression)内部的内容,从粗略的外观来看,该调用获取输入元素上的 name html 属性。member.Name

我现在还不能完全验证它,因为我不在 Windows 上,但我认为非 lambda 函数应该适合您的需要。请告诉我进展如何?