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

  • BenjiManTV

    BenjiManTV

    20 Mart 2011
  • Justin Schenck

    Justin Schen

    24 Kasım 2006
  • Project Mooncircle

    Project Moon

    6 Aralık 2009