我正在尝试将 css 类添加到 EditorTemplate 上的 Html.LabelFor
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })
我的期望例如:标签应该选择 css 类。
为此,我尝试使用以下代码扩展标签,但我的标签没有显示。 我在这里做错了什么?
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, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, 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 根据用户操作更改标签样式。在我的页面上一切都很好,除了我无法扩展和添加 css 类到我的标签。
最佳答案
我怀疑您忘记将定义此 LabelExtensions 类的命名空间带入 View 的范围内。例如,如果此类是在 MyProject.Extensions
命名空间内定义的:
namespace MyProject.Extensions
{
public static class LabelExtensions
{
...
}
}
确保您已将此命名空间纳入范围:
@using MyProject.Extensions
@model MyViewModel
...
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })
关于asp.net-mvc-3 - 扩展 MVC3 razor Html.LabelFor 添加 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10603016/