如何获取属性的表单名称

kel*_*oti 4 forms http-post asp.net-mvc-3

在Razor我知道如果你写

@Html.HiddenFor(x => x.PropertyX.PropertyY)
Run Code Online (Sandbox Code Playgroud)

它将生成HTML,如:

<input type="hidden" name="PropertyX.PropertyY" value="...">
Run Code Online (Sandbox Code Playgroud)

并且(特别是)如果这是在编辑器模板中,它可能会生成此HTML:

<input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" value="...">
Run Code Online (Sandbox Code Playgroud)

如何获取任意属性的名称?我假设必须有一些方法来使用MVC基础设施(可能是一些方法或类?)

Dar*_*rov 8

你可以为此编写一个自定义助手:

public static class NameExtensions
{
    public static string NameFor<TModel, TProperty>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TProperty>> expression
    )
    {
        var partialName = ExpressionHelper.GetExpressionText(expression);
        return html
            .ViewContext
            .ViewData
            .TemplateInfo
            // You could do the same with GetFullHtmlFieldId
            // if you were interested in the id of the element
            .GetFullHtmlFieldName(partialName);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

@Html.NameFor(x => x.PropertyX.PropertyY)
Run Code Online (Sandbox Code Playgroud)

  • 现在这已经在MVC 4 [问题](http://stackoverflow.com/questions/3444021/htmlhelper-namefor-method)和[MSDN link here](http://msdn.microsoft.com/en-)中得到了体现.我们/库/ hh833703(v = vs.108)的.aspx) (3认同)