I have created the following code to render a table from below array
var fruit = new string[] { "apple", "pear", "tomato" };
public static MvcHtmlString CustomGrid(this HtmlHelper htmlHelper, String Id, IList Items, IDictionary<string, string> Attributes)
{
if (Items == null || Items.Count == 0 || string.IsNullOrEmpty(Id))
return MvcHtmlString.Empty;
return BuildGrid(Items, Id, Attributes);
}
public static MvcHtmlString BuildGrid(IList Items, string Id, IDictionary<string, string> attributes)
{
StringBuilder sb = new StringBuilder();
BuildHeader(sb, Items[0].GetType());
foreach (var item in Items)
{
BuildTableRow(sb, item);
}
TagBuilder builder = new TagBuilder("table");
builder.MergeAttributes(attributes);
builder.MergeAttribute("name", Id);
builder.InnerHtml = sb.ToString();
var Tag = builder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(Tag);
}
public static void BuildTableRow(StringBuilder sb, object obj)
{
Type objType = obj.GetType();
sb.AppendLine("\t<tr>");
foreach (var property in objType.GetProperties())
{
sb.AppendFormat("\t\t<td>{0}</td>\n", property.GetValue(obj, null));
// sb.AppendFormat("\t\t<td>{0}</td>\n", obj);
}
sb.AppendLine("\t</tr>");
}
public static void BuildHeader(StringBuilder row, Type p)
{
row.AppendLine("\t<tr>");
foreach (var property in p.GetProperties())
{
开发者_Python百科 row.AppendFormat("\t\t<th>{0}</th>\n", p.Name);
}
row.AppendLine("\t</tr>");
}
but it doesn't render any thing. I am using it like this:
Html.CustomGrid("myTable", (System.Collections.IList)fruit, null);
Please suggest solution to it.
First put in some debugging statements to make sure anything is coming from the output. If its not, you are likely not using is like @Html.CustomGrid and instead using it in a code block where the output is not rendered to the response stream.
You're missing the @ from Html.CustomGrid("myTable", (System.Collections.IList)fruit, null);
精彩评论