http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspxから大きく借りて、これを行う拡張メソッドを作成しました。常に安全なスパンタグで出力します。また、これを変更してスパンタグを完全に省略することもできます(この場合、属性を決して使用できないため、2つのオーバーロードを排除します)。
は、あなたのページは、その後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