Created
June 27, 2013 14:10
-
-
Save bitsprint/5876720 to your computer and use it in GitHub Desktop.
HtmlHelper Extensions
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
| namespace Web.Extensions.Control | |
| { | |
| public static partial class HtmlHelperExtensions | |
| { | |
| // Usage: @Html.ListBoxWithAttributesFor(m => m.Foo, Model.Foos, false) | |
| // See SelectListItemWithAttributes | |
| public static MvcHtmlString ListBoxWithAttributesFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItemWithAttributes> selectList, bool multiple = true) | |
| { | |
| if (expression == null) | |
| { | |
| throw new ArgumentNullException("expression"); | |
| } | |
| var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); | |
| var name = ExpressionHelper.GetExpressionText(expression); | |
| var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); | |
| var listItemBuilder = new StringBuilder(); | |
| if (selectList != null) | |
| { | |
| selectList.ForEach(item => listItemBuilder.AppendLine(ListItemToOption(item))); | |
| } | |
| var tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; | |
| if (multiple) | |
| { | |
| tagBuilder.MergeAttribute("multiple", "multiple"); | |
| } | |
| tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */); | |
| tagBuilder.GenerateId(fullName); | |
| // If there are any errors for a named field, we add the css attribute. | |
| ModelState modelState; | |
| if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) | |
| { | |
| if (modelState.Errors.Count > 0) | |
| { | |
| tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); | |
| } | |
| } | |
| tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)); | |
| return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); | |
| } | |
| private static string ListItemToOption(SelectListItemWithAttributes item) | |
| { | |
| var builder = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) }; | |
| if (item.Value != null) | |
| { | |
| builder.Attributes["value"] = item.Value; | |
| } | |
| if (item.Selected) | |
| { | |
| builder.Attributes["selected"] = "selected"; | |
| } | |
| if (item.Attributes != null) | |
| { | |
| item.Attributes.ForEach(attribute => { builder.Attributes[string.Concat("data-", attribute.Key)] = attribute.Value.ToString(); }); | |
| } | |
| return builder.ToString(TagRenderMode.Normal); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment