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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....