Sto cercando di aggiungere una classe CSS per Html.LabelFor su un EditorTemplateEstendere MVC3 rasoio Html.LabelFor aggiungere classe CSS
@Html.LabelFor(model => model.Name, new { @class = "myLabel" })
la mia aspettativa per esempio: etichetta deve raccogliere la classe CSS.
Per questo ho provato ad estendere Label con il seguente codice, ma la mia etichetta non viene visualizzata. Cosa sto facendo di sbagliato qui?
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));
}
}
Se non sto specificando classe CSS per esempio @Html.LabelFor(model => model.Name)
, poi mostra l'etichetta. Ma non sono in grado di applicare css alla mia etichetta. Voglio mostrare l'etichetta di colore blu, quando la pagina viene caricata., Quindi cambiare lo stile dell'etichetta in base all'azione dell'utente usando jquey.Tutto sta bene, sulla mia pagina tranne il fatto che non riesco ad estendere e aggiungere un css classe alla mia etichetta.
Si prega di definire "non funziona". Qual è il risultato che ti aspetti e qual è il risultato che ricevi? – Aaronaught
Che problema stai avendo? –