【问题标题】:C# ASP.net EditorTemplate - get name of the used model propertyC# ASP.net EditorTemplate - 获取使用的模型属性的名称
【发布时间】:2011-11-07 11:48:46
【问题描述】:

我有一个剃刀观点,我称之为:

@Html.EditorFor(m => m.Code)

然后我有一个 EditorTemplate 视图然后呈现,它看起来像这样:

@model string
@Html.HiddenFor(m=>m)

我得到这个输出:

<input id="Code" name="Code" type="hidden" value="" />

一切都好。

但现在我只想在 EditorTemplate 视图中获取属性名称 Code,而不是整个输入字符串。 @Html.HiddenFor(m=&gt;m) 方法能够以某种方式从模型对象中获取它并将其放入输入字段中,但我该怎么做呢?

(不,我不想从输入字段字符串中解析它... :)

【问题讨论】:

    标签: c#-4.0


    【解决方案1】:

    @Html.HiddenFor(m=&gt;m) 看起来有点奇怪……但无论如何:

    HiddenFor 使用 Expression&lt;Func&lt;TModel, TProperty&gt;&gt;,因此您可以创建自己的函数以仅返回名称:

     public static class GenericHelper<T>
     {
         public static String GetPropertyName<TValue>(Expression<Func<T, TValue>> propertyId)
         {
             var operant = (MemberExpression)((UnaryExpression)propertyId.Body).Operand;
             return operant.Member.Name;
         }
    }
    

    并创建一个助手以在您的视图中使用它,这在here 中进行了解释

    【讨论】:

    • 我真的不使用@Html.HiddenFor(m=>m),我只是想表明帮助者能够得到我想要的东西。感谢你的回答!这些表达式我得稍微挖掘一下,我不是很熟悉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2017-01-13
    相关资源
    最近更新 更多