有没有办法使用LabelFor帮助器并自定义标签文本,而不必在我的模型中使用DisplayNameAttribute?
解决方法
我为我的项目创建了这个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 labelText,object htmlAttributes) { return Label(htmlHelper,new RouteValueDictionary(htmlAttributes)); } public static MvcHtmlString Label(this HtmlHelper htmlHelper,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,(object) null); } public static MvcHtmlString LabelFor<TModel,object htmlAttributes) { return LabelFor(htmlHelper,new RouteValueDictionary(htmlAttributes)); } public static MvcHtmlString LabelFor<TModel,object> htmlAttributes) { string inputName = ExpressionHelper.GetExpressionText(expression); return htmlHelper.Label(inputName,htmlAttributes); } }
我用“强类型”资源使用它们:
<%= Html.LabelFor(m=>m.NickName,UserStrings.NickName) %>
希望有帮助…
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。