Skip to content

Instantly share code, notes, and snippets.

@bitsprint
Created June 27, 2013 14:10
Show Gist options
  • Select an option

  • Save bitsprint/5876720 to your computer and use it in GitHub Desktop.

Select an option

Save bitsprint/5876720 to your computer and use it in GitHub Desktop.
HtmlHelper Extensions
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