Created
August 3, 2011 18:51
-
-
Save KevM/1123473 to your computer and use it in GitHub Desktop.
Mini How To Make a drop down via Html Convention
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
| //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; | |
| } | |
| } |
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 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