asp.net MVC3自定义助手无法正常工作

时间:2011-04-19 15:06:47

标签: asp.net asp.net-mvc-3

我创建了以下代码来从数组

下面呈现一个表
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())
        {
            row.AppendFormat("\t\t<th>{0}</th>\n", p.Name);
        }
        row.AppendLine("\t</tr>");
    }

但它不会呈现任何东西。我这样使用它:

Html.CustomGrid("myTable", (System.Collections.IList)fruit, null);

请建议解决方案。

2 个答案:

答案 0 :(得分:1)

首先输入一些调试语句,以确保任何来自输出。如果没有,你很可能不会使用@ Html.CustomGrid,而是在代码块中使用它,而不会将输出呈现给响应流。

答案 1 :(得分:0)

你错过了@ from     Html.CustomGrid(“myTable”,(System.Collections.IList)fruit,null);