加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Asp.Net MVC 2 Label自定义文本

发布时间:2020-12-16 00:40:13 所属栏目:asp.Net 来源:网络整理
导读:有没有办法使用LabelFor帮助器并自定义标签文本,而不必在我的模型中使用DisplayNameAttribute? 解决方法 我为我的项目创建了这个html助手: public static class MyLabelExtensions{ public static MvcHtmlString Label(this HtmlHelper htmlHelper,string
有没有办法使用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) %>

希望有帮助…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读