Created
January 18, 2013 13:02
-
-
Save BlackPrincess/4564426 to your computer and use it in GitHub Desktop.
MVC3 LabelFor拡張
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Web.Mvc; | |
| using System.Web.Routing; | |
| using System.Linq.Expressions; | |
| public static class LabelExtensions | |
| { | |
| 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)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment