如何获取表单名称为属性 [英] How to get the form name for a property
本文介绍了如何获取表单名称为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在剃刀我知道,如果你写
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)
这篇关于如何获取表单名称为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文