19 ŞUBAT 2010, Cuma
.Html için bir sınıf atamak için Nasıl NET MVC -.LabelFor?
Bu kod
<%= Html.LabelFor(model => model.Name) %>
üretir bu
<label for="Name">Name</label>
Ama bunu istiyorum
<label for="Name" class="myLabel">Name</label>
Bunu nasıl yaparsınız?
CEVAP
18 NİSAN 2011, PAZARTESİ
LabelFor aşırı yük:
public static class NewLabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.SetInnerText(labelText);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
Bunu Paylaş:
Nasıl bir HTML kabı için birden fazla ...
Nasıl Açısal JS satır için başka bir s...
Nasıl sadece sayısal (0-9) HTML ınputb...
Nasıl bir bağlantı gibi davranan bir H...
Nasıl HTML Çeviklik paketi kullanmak i...