【问题标题】:asp.net mvc html helpers using property name使用属性名称的 asp.net mvc html 助手
【发布时间】: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


【解决方案1】:

只需@Html.Hidden("SomeProperty")

【讨论】:

  • 嘿@max,不知道这如何解决问题。我已经编辑了我的问题,这是否让我的目标更加清晰?
  • @TechplexEngineer 抱歉,我以为 Model.modelRecId 有属性名称,请参阅我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多