且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Asp.Net MVC 2 LabelFor自定义文本

更新时间:2023-02-25 10:11:05

我创建这个网站的助手为我的项目:

I have created this html helpers for my project:

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);
    }
}

我使用它们以强类型的资源:

I use them with "strongly typed" resources:

<%= Html.LabelFor(m=>m.NickName, UserStrings.NickName) %>

希望帮助...

Hope that helps...