Created
May 8, 2012 15:02
-
-
Save frankgeerlings/2635991 to your computer and use it in GitHub Desktop.
ASP.NET MVC: SELECT with OPTGROUP from dictionary of select list items
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
public static class HtmlExtensions | |
{ | |
public static IHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Dictionary<string, IEnumerable<SelectListItem>> selectList) | |
{ | |
/* | |
* <select name="tmodel"> | |
* <optgroup title="Items"> | |
* <option value="item">Item</option> | |
* </select> | |
*/ | |
var select = new TagBuilder("select"); | |
select.Attributes.Add("name", ExpressionHelper.GetExpressionText(expression)); | |
var optgroups = new StringBuilder(); | |
foreach (var kvp in selectList) | |
{ | |
var optgroup = new TagBuilder("optgroup"); | |
optgroup.Attributes.Add("label", kvp.Key); | |
var options = new StringBuilder(); | |
foreach (var item in kvp.Value) | |
{ | |
var option = new TagBuilder("option"); | |
option.Attributes.Add("value", item.Value); | |
option.SetInnerText(item.Text); | |
if (item.Selected) | |
{ | |
option.Attributes.Add("selected", "selected"); | |
} | |
options.Append(option.ToString(TagRenderMode.Normal)); | |
} | |
optgroup.InnerHtml = options.ToString(); | |
optgroups.Append(optgroup.ToString(TagRenderMode.Normal)); | |
} | |
select.InnerHtml = optgroups.ToString(); | |
return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh. There's some opportunity for HTML injection here. Should probably escape some strings.