Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Forms 如何获取属性的表单名称_Forms_Asp.net Mvc 3_Http Post - Fatal编程技术网

Forms 如何获取属性的表单名称

Forms 如何获取属性的表单名称,forms,asp.net-mvc-3,http-post,Forms,Asp.net Mvc 3,Http Post,在Razor我知道如果你写 @Html.HiddenFor(x => x.PropertyX.PropertyY) 它将生成HTML,如: <input type="hidden" name="PropertyX.PropertyY" value="..."> 而且(特别是)如果这是在编辑器模板中,它可能会生成以下HTML: <input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" val

在Razor我知道如果你写

@Html.HiddenFor(x => x.PropertyX.PropertyY)
它将生成HTML,如:

<input type="hidden" name="PropertyX.PropertyY" value="...">

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

<input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" value="...">


如何获取任意属性的名称?我假设使用MVC基础设施(可能是某种方法或类?)一定有办法做到这一点。

您可以为此编写自定义帮助程序:

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);
    }
}

这并不完全符合德米特定律,但它让我摆脱了束缚。谢谢这现在在MVC4和a中实现
@Html.NameFor(x => x.PropertyX.PropertyY)