1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
public static string ToFormattedList<T>(this HtmlHelper helper, IList<T> objectList, ListType listType, Func<T, string> valueReturn) { string outerListFormat = ""; string listFormat = ""; switch (listType) { case ListType.Ordered: outerListFormat = "<ol>{0}</ol>"; listFormat = "<li>{0}</li>"; break; case ListType.Unordered: outerListFormat = "<ul>{0}</ul>"; listFormat = "<li>{0}</li>"; break; case ListType.TableCell: outerListFormat = "{0}"; listFormat = "<td>{0}</td>"; break; default: break; } var sb = new StringBuilder(); objectList.ForEach(item => sb.AppendFormat(listFormat, valueReturn(item))); return string.Format(outerListFormat, sb); } public enum ListType { Ordered, Unordered, TableCell }
Usage:
1
Html.ToFormattedList(item.Groups, UiHelpers.ListType.Unordered, g => g.GroupName )
Refactorings
No refactoring yet !
Ants
January 26, 2010, January 26, 2010 06:13, permalink
I don't get to do much ASP.NET MVC work, but I really subscribe to the philosophy it has of keeping the markup in as separate from the code as possible. My preference would be to go with the approach shown here:
http://haacked.com/archive/2008/05/03/code-based-repeater-for-asp.net-mvc.aspx
With the code above, I like the way a StringBuilder is used for efficiency, but all that lost when applying the formatting. How about something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
public static string ToFormattedList<T>(IList<T> objectList, Func<T, string> valueReturn, string outerPrefix, string outerSuffix, string innerPrefix, string innerSuffix) { var sb = new StringBuilder(); sb.Append(outerPrefix); foreach(T item in objectList) { sb.Append(innerPrefix); sb.Append(valueReturn(item)); sb.Append(innerSuffix); } sb.Append(outerSuffix); return sb.ToString(); } public static string ToFormattedList<T>(this HtmlHelper helper, IList<T> objectList, ListType listType, Func<T, string> valueReturn) { switch (listType) { case ListType.Ordered: return ToFormattedList<T>(objectList, valueReturn, "<ol>", "</ol>", "<li>", "</li>"); case ListType.Unordered: return ToFormattedList<T>(objectList, valueReturn, "<ul>", "</ul>", "<li>", "</li>"); case ListType.TableCell: return ToFormattedList<T>(objectList, valueReturn, "", "", "<td>", "</td>"); } return ToFormattedList<T>(objectList, valueReturn, "", "", "", ""); } public enum ListType { Ordered, Unordered, TableCell }
Usage:
1
Html.ToFormattedList(item.Groups, UiHelpers.ListType.Unordered, g => g.GroupName )
I wanted to display list from my object:
user[x].Group[y].Name
I got some of code from here: http://blog.wekeroad.com/blog/asp-net-mvc-list-helper-extension-method/
I'm wondering if there is a better way.