微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc-3 – 扩展MVC3剃刀Html.LabelFor添加css类

我试图在EditorTemplate上添加一个css类到 Html.LabelFor
@Html.LabelFor(model => model.Name,new { @class = "myLabel" })

我的期望例如:标签应该拿起css类.

为此,我尝试使用以下代码扩展Label,但是我的标签没有显示.
在这里做错了什么?

public static class LabelExtensions
    {
        public static MvcHtmlString LabelFor<TModel,TValue>(this HtmlHelper<TModel> html,Expression<Func<TModel,TValue>> expression,object htmlAttributes)
        {
            return html.LabelFor(expression,null,htmlAttributes);
        }

        public static MvcHtmlString LabelFor<TModel,string labelText,object htmlAttributes)
        {
            return html.LabelHelper(
                ModelMetadata.FromLambdaExpression(expression,html.ViewData),ExpressionHelper.GetExpressionText(expression),HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),labelText);
        }

        private static MvcHtmlString LabelHelper(this HtmlHelper html,ModelMetadata Metadata,string htmlFieldName,IDictionary<string,object> htmlAttributes,string labelText = null)
        {
            var str = labelText
                ?? (Metadata.displayName
                ?? (Metadata.PropertyName
                ?? htmlFieldName.Split(new[] { '.' }).Last()));

            if (string.IsNullOrEmpty(str))
                return MvcHtmlString.Empty;

            var tagBuilder = new TagBuilder("label");
            tagBuilder.MergeAttributes(htmlAttributes);
            tagBuilder.Attributes.Add("for",TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
            tagBuilder.SetInnerText(str);

            return tagBuilder.ToMvcHtmlString(TagRenderMode.normal);
        }

        private static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder,TagRenderMode renderMode)
        {
            return new MvcHtmlString(tagBuilder.ToString(renderMode));
        }
    }

如果我没有指定css类,例如@ Html.LabelFor(model => model.Name),那么它显示标签.
但我不能将CSS应用于我的标签.
我想要显示蓝色的标签,当页面加载时,然后根据用户操作改变标签样式使用jquey.All是罚款,在我的页面,除了我无法扩展和添加一个css类到我的标签

解决方法

我怀疑你忘了把您在其中定义的LabelExtensions类的命名空间放在视图中.所以例如如果这个类是在MyProject.Extensions命名空间内定义的:
namespace MyProject.Extensions
{
    public static class LabelExtensions
    {
        ...
    }
}

确保您已将此命名空间带入范围:

@using MyProject.Extensions
@model Myviewmodel
...
@Html.LabelFor(model => model.Name,new { @class = "myLabel" })

原文地址:https://www.jb51.cc/aspnet/250603.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐