I am trying to create a specific HtmlHelper table extension to reduce the spaghetti code in my View.
Taking a list of domain objects I would like to display a table that is a little bit more intelligent in using the properties of the domain object as columns. In addition, I would like to disable showing of some properties as columns. An idea would be to decorate properties with attributes that tell it not to be shown.
Hopefully that makes sense but here's where I got to so far...
public static string MyTable(this HtmlHelper helper, string name,
IList<MyObject> items, object tableAttributes)
{
if (items == null || items.Count == 0)
return String.Empty;
StringBuilder sb = new StringBuilder();
BuildTableHeader(sb, items[0].GetType());
//TODO: to be implemented...
//foreach (var i in items)
// BuildMyObjectTableRow(sb, i);
TagBuilder builder = new TagBuilder("table");
builder.MergeAttributes(new RouteValueDictionary(tableAttributes));
builder.MergeAttribute("name", name);
builder.InnerHtml = sb.ToString();
return builder.ToString(TagRenderMode.Normal);
}
private static void BuildTableHeader(StringBuilder sb, Type p)
{
sb.AppendLine("<tr>");
//some how here determine if this property should be shown or not
//this could possibly come from an attribute defined on the property
foreach (var property in p.GetProperties())
sb.AppendFormat("<th>{0}</th>", property.Name);
sb.AppendLine("</tr>");
}
//would be nice to do something like this below to determine what
//should be shown in the table
[TableBind(Include="Property1,Property2,Property3")]
public partial class MyObject
{
...properties are defined as Linq2Sql
}
So I was just wondering if anyone had any opinions/suggestions on this idea or any alternatives?
Looks good so far, but Gil Fink may have already done the work for you here: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/01/13/extending-asp-net-mvc-htmlhelper-class.aspx
I strongly suggest to use MvcContrib's Grid. If you decide not to, at least you can take a look at how they solved the table generation interface problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With