借用http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx,我创建了一个扩展方法来执行此操作。它带有始终安全的跨度标签输出。你也可以修改这个来完全省略span标签(消除两个重载,因为在这种情况下你永远不能获取属性)。
与此内容创建一个类时,请确保您的网页导入该类的命名空间,然后在视图中使用这个喜欢Html.DisplayNameFor(x => x.Name)
public static class DisplayNameForHelper
{
public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return DisplayNameFor(html, expression, new RouteValueDictionary());
}
public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return DisplayNameFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("span");
tag.MergeAttributes(htmlAttributes);
tag.SetInnerText(labelText);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
感谢达林!这就是我需要的。 – kseen