我正在为编辑器编写 HTML Helper。这个想法是从具有属性 AutoGenerateField 的模型中获取属性并构建一个表,其中的每一行都包含一个字段的名称(也来自该属性)和一个包含该字段实际值的 TextBox 或 CheckBox。
我有 HTMLHelper 的问题。由于我将整个模型发送给助手而不是一个值,因此我不能使用诸如 TextBoxFor 之类的方法,因为它们需要参数,例如
"Expression<Func<TModel, TValue>> expression".
我正在使用反射并尝试发送属性,但 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);
}
有任何想法吗?
最佳答案
只使用非 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...
如果我没记错的话
name
即使您使用函数的 lambda 版本,表单元素的属性也设置为属性名称,因此这应该做同样的事情。我将尝试验证 lambda 函数的作用,因为您拥有
TModel
,所以您可能也可以这样做。和你。更新
来自 快速浏览 InputExtensions.cs源代码里面的东西, TextBoxFor 调用最终调用
InputHelper()
最终调用 ExpressionHelper.GetExpressionText(LambdaExpression expression)
内ExpressionHelper.cs从粗略的外观来看,这是member.Name
对于 input 元素上的 name html 属性。我现在无法完全验证它,因为我不在 Windows 上,但我认为非 lambda 函数应该适合您的需要。请告诉我进展如何?
关于asp.net-mvc - HTMLHelper,在属性外生成 "Expression<Func<TModel, TValue>> expression"类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107812/