有没有办法使用LabelFor助手并自定义标签文本而不必在我的模型中使用DisplayNameAttribute?
rre*_*ejc 20
我为我的项目创建了这个html助手:
public static class MyLabelExtensions
{
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText)
{
return Label(htmlHelper, forName, labelText, (object) null);
}
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
object htmlAttributes)
{
return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
IDictionary<string, object> htmlAttributes)
{
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("for", forName.Replace(".", tagBuilder.IdAttributeDotReplacement), true);
tagBuilder.SetInnerText(labelText);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText)
{
return LabelFor(htmlHelper, expression, labelText, (object) null);
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText, object htmlAttributes)
{
return LabelFor(htmlHelper, expression, labelText, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText,
IDictionary<string, object> htmlAttributes)
{
string inputName = ExpressionHelper.GetExpressionText(expression);
return htmlHelper.Label(inputName, labelText, htmlAttributes);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用"强类型"资源:
<%= Html.LabelFor(m=>m.NickName, UserStrings.NickName) %>
Run Code Online (Sandbox Code Playgroud)
希望有帮助......
| 归档时间: |
|
| 查看次数: |
10171 次 |
| 最近记录: |