Skip to content

Instantly share code, notes, and snippets.

@eduardocp
Created November 6, 2014 11:26
Show Gist options
  • Select an option

  • Save eduardocp/1fba6562ee5d0a5baec4 to your computer and use it in GitHub Desktop.

Select an option

Save eduardocp/1fba6562ee5d0a5baec4 to your computer and use it in GitHub Desktop.
public class GroupedDropDownList
{
public string Name { get; set; }
public List<SelectListItem> Values { get; set; }
public GroupedDropDownList()
{
Values = new List<SelectListItem>();
}
}
public static partial class SelectExtensions
{
public static MvcHtmlString GroupedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string optionalLabel, IEnumerable<GroupedDropDownList> selectList, object htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
string name = ExpressionHelper.GetExpressionText(expression);
return GroupedDropDownList(htmlHelper, name, optionalLabel, selectList, htmlAttributes);
}
public static MvcHtmlString GroupedDropDownList(this HtmlHelper htmlHelper, string name, string optionalLabel, IEnumerable<GroupedDropDownList> selectList, object htmlAttributes)
{
TagBuilder drop = new TagBuilder("select");
drop.MergeAttribute("name", name);
drop.MergeAttribute("id", name);
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
drop.MergeAttributes(attributes);
}
IDictionary<string, object> validationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(name);
drop.MergeAttributes(validationAttributes);
if (optionalLabel != null && !string.IsNullOrEmpty(optionalLabel))
{
TagBuilder optLbl = new TagBuilder("option");
optLbl.MergeAttribute("value", "");
optLbl.InnerHtml = optionalLabel;
drop.InnerHtml += optLbl.ToString();
}
foreach (var group in selectList)
{
TagBuilder g = new TagBuilder("optgroup");
g.Attributes.Add("label", group.Name);
foreach (var option in group.Values)
{
TagBuilder opt = new TagBuilder("option");
if (option.Selected)
{
opt.MergeAttribute("selected", "selected");
}
opt.MergeAttribute("value", option.Value);
opt.InnerHtml = option.Text;
g.InnerHtml += opt.ToString();
}
drop.InnerHtml += g.ToString();
}
return new MvcHtmlString(drop.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment