Skip to content

Instantly share code, notes, and snippets.

@KevM
Created August 3, 2011 18:51
Show Gist options
  • Select an option

  • Save KevM/1123473 to your computer and use it in GitHub Desktop.

Select an option

Save KevM/1123473 to your computer and use it in GitHub Desktop.
Mini How To Make a drop down via Html Convention
//annotate your view model property with this attribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class GbstListValueAttribute : Attribute
{
private readonly string _listName;
public GbstListValueAttribute(string listName)
{
_listName = listName;
}
public virtual string GetListName(Type type)
{
return _listName;
}
}
public class GbstListValueDropdownBuilder : ElementBuilder
{
protected override bool matches(AccessorDef def)
{
var hasAttribute = def.Accessor.HasAttribute<GbstListValueAttribute>();
return hasAttribute;
}
public override HtmlTag Build(ElementRequest request)
{
return new SelectTag(tag =>
{
var defaultValue = buildOptions(request, tag);
tag.SelectByValue(defaultValue);
});
}
private static string buildOptions(ElementRequest request, SelectTag tag)
{
var defaultValue = request.Value<string>();
var listElements = GetListElementsOrderedByRank(request);
foreach (var e in listElements)
{
if (e.IsDefault && defaultValue.IsEmpty()) defaultValue = e.Title;
tag.Option(e.Title, e.Title);
}
return defaultValue;
}
private static IEnumerable<ListElement> GetListElementsOrderedByRank(ElementRequest request)
{
var att = request.Accessor.GetAttribute<GbstListValueAttribute>();
var listName = att.GetListName(request.Accessor.OwnerType);
var listCache = request.Get<IListCache>();
var gbstList = listCache.GetGbstList(listName);
return gbstList.ActiveElements
.OrderBy(e => e.Rank)
.Select(element => new ListElement
{
Title = element.Title,
IsDefault = element.Equals(gbstList.DefaultElement)
});
}
private class ListElement
{
public string Title { get; set; }
public bool IsDefault { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment