SORU
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));
    }
}

http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • andyabc45

    andyabc45

    1 Mayıs 2011
  • Ash100HD

    Ash100HD

    29 EKİM 2011
  • Hot For Nutrition

    Hot For Nutr

    26 ŞUBAT 2007