【发布时间】:2013-07-27 00:09:38
【问题描述】:
我正在尝试使用字符串模型属性名称列表来制作表单。当使用这样的脚手架代码时:
@Html.HiddenFor(model => model.modelRecId)
我认为使用反射可以得到与这样的代码相同的结果:
@Html.HiddenFor(model => model.GetType().GetProperty("modelRecId").GetValue(model, null))
遗憾的是,c# 不喜欢这种语法,产生了这个错误:Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
对于如何使用将属性名称作为字符串给出的内置 html 助手有什么想法吗?
编辑:
List<string> props = new List<string>();
props.Add("modelRecId");
props.Add("Name");
props.Add("Description");
//... etc
foreach (string prop in props)
{
@Html.LabelFor(Model.GetType().GetProperty(prop).GetValue(Model, null), prop)
@Html.EditorFor(Model.GetType().GetProperty(prop).GetValue(Model, null))
@Html.ValidationMessageFor(Model.GetType().GetProperty(prop).GetValue(Model, null))
}
上面的代码不起作用。有没有办法做这样的事情?
【问题讨论】:
-
我不确定有没有办法使用内置的
HtmlHelper方法来做到这一点;但是,您当然可以编写自己的HtmlHelper扩展方法来为您执行此操作。
标签: asp.net-mvc