如何获取表单名称为属性
问题描述:
在剃刀我知道,如果你写
In Razor I know that if you write
@Html.HiddenFor(x => x.PropertyX.PropertyY)
它会生成HTML这样的:
it will generate HTML like:
<input type="hidden" name="PropertyX.PropertyY" value="...">
和(特别是)如果这是在编辑模板它可能会产生这样的HTML:
And (especially) if this was in an Editor Template it might generate this HTML:
<input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" value="...">
我如何获得一个任意属性的名称?我猜想一定是有办法做到这一点使用MVC的基础设施(也许还有一些方法或类?)
How do I get a name for an arbitrary property? I'm assuming there must be some way to do this using MVC infrastructure (perhaps some method or class?)
答
您可以编写一个自定义的帮手是:
You could write a custom helper for that:
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);
}
}
和则:
@Html.NameFor(x => x.PropertyX.PropertyY)