Forms 如何获取属性的表单名称
在Razor我知道如果你写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
@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)