框架用来构建名称的类(不是每个 ID)是一个静态类ExpressionHelper
,它在 MVC3 中是可公开访问的。它有一个名为的函数GetExpressionText
,它接受一个 lambda。话虽如此,您必须制作自己的 IdFor 包装器才能从中获取所需的语法。
这是 MVC4 中存在的类:
public static class NameExtensions
{
public static MvcHtmlString Id(this HtmlHelper html, string name)
{
return MvcHtmlString.Create(html.AttributeEncode(html.ViewData.TemplateInfo.GetFullHtmlFieldId(name)));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]
public static MvcHtmlString IdFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
return Id(html, ExpressionHelper.GetExpressionText(expression));
}
public static MvcHtmlString IdForModel(this HtmlHelper html)
{
return Id(html, String.Empty);
}
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "1#", Justification = "This is a shipped API.")]
public static MvcHtmlString Name(this HtmlHelper html, string name)
{
return MvcHtmlString.Create(html.AttributeEncode(html.ViewData.TemplateInfo.GetFullHtmlFieldName(name)));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]
public static MvcHtmlString NameFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
return Name(html, ExpressionHelper.GetExpressionText(expression));
}
public static MvcHtmlString NameForModel(this HtmlHelper html)
{
return Name(html, String.Empty);
}
}