Mil*_*lar 14 razor c#-4.0 asp.net-mvc-3
我想在EditorTemplate上为Html.LabelFor添加一个css类
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })
Run Code Online (Sandbox Code Playgroud)
我的期望例如:label应该拿起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, 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));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我没有指定css类 @Html.LabelFor(model => model.Name) ,那么它会显示标签.但我无法将css应用于我的标签.我希望在页面加载时以蓝色显示标签.然后使用jquey更改基于用户操作的标签样式.在我的页面上很好,除了我无法扩展并添加css类这一事实到我的标签.
Dar*_*rov 16
我怀疑您忘记了在视图中将此LabelExtensions类定义在其范围内的命名空间.因此,例如,如果在MyProject.Extensions命名空间内定义了此类:
namespace MyProject.Extensions
{
public static class LabelExtensions
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
确保您已将此命名空间纳入范围:
@using MyProject.Extensions
@model MyViewModel
...
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })
Run Code Online (Sandbox Code Playgroud)