如何使用动态模型创建动态table

How to use a dynamic model to create a dynamic table

我想做一个table,所以我可以加载一个class进去,table会自动生成。

这就是我要找的东西,但我不知道如何实现:

@model dynamic
<table>
<thead>
    <tr>
    @foreach(var record in model.results)
    {
        <th>@Html.labelfor(item.indexof(...))</th>
    }

    </tr>
</thead>
@if (Model.Result.Count() > 0)
{
    <tbody>
        @for(int i = 0; i < Model.Result.Count(); i++)
        {
            <tr>
                @foreach (var item in Model.Result)
                {  
                    <td>@item.indexOf(...)</td>
                }
            </tr>
        }
    </tbody>
}
else
{
    <p class="errordata">No data found...</p>
}

这是我的视图模型:

public class issueModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }
    public string FontColor { get; set; }
    public int Count { get; set; }
    public string Description { get; set; }
    public string Abbreviation { get; set; }
    public string icon { get; set; }
    public List<dynamic> Result { get; set; }
}

中的"List result"可以不同,这是一个示例class,结果可能是:

public partial class someClass
{
    [Display(Name = "PID_1")]
    public int? someProp_1{ get; set; }

    [Display(Name = "PID_2")]
    public int? someProp_2{ get; set; }

    [StringLength(255)]
    public string PermName1 { get; set; }

    [StringLength(255)]
    public string PermName2 { get; set; }

    public string description{ get; set; }

    public int? Prioriteit { get; set; }

    [StringLength(50)]
    public string Login { get; set; }

    public int id{ get; set; }
}

我尝试在动态项上使用 .indexOf,但这不起作用。以某种方式做到这一点吗?或者我是否必须使用单独的 tables 制作单独的视图?

您需要对此场景进行反思。您应该构建一个新的 Html Helper。此助手遍历模型的所有 public 属性,并使用该信息创建 table,然后您只需要在视图中调用助手:

助手Class:

namespace System.Web.Mvc
{
    public static class TableHelperExtensions
    {
        public static string BuildTr(object _obj)
        {
            var properties = _obj.GetType().GetProperties();
            var tr = "<tr>";

            foreach(var property in properties) {
                tr += String.Format("<td>{0}</td>", property.GetValue(_obj));
            }

            tr += "</tr>";

            return (tr);
        }

        public static string BuildTrHeader(object _obj)
        {
            var properties = _obj.GetType().GetProperties();
            var tr = "<tr>";

            foreach (var property in properties)
            {
                tr += String.Format("<th>{0}</th>", property.Name);
            }

            tr += "</tr>";

            return (tr);
        }

        public static HtmlString BuildTable(this HtmlHelper helper, object _obj)
        {
            if(!IsCollection(_obj.GetType())) {
                throw new InvalidOperationException("BuildTable helper can be called only on collection object");
            }

            var tableStart = String.Format(@"<table>
                            <thead>
                                {0}
                            </thead>
                            <tbody>", BuildTrHeader((_obj as IEnumerable<object>).ElementAt(0)));

            var tableBody = String.Empty;

            var coll = _obj as IEnumerable<object>;

            foreach(var _ in coll){
                tableBody += BuildTr(_);
            }

            var tableEnd = @"
                            </tbody>
                        </table>";;

            return new HtmlString(tableStart + tableBody + tableEnd);
        }

        static bool IsCollection(Type type)
        {
            return type.GetInterface(typeof(IEnumerable<>).FullName) != null;
        } 
    }
}

示例视图:

@{
    Layout = null;

    var objs = new List<object>();

    objs.Add(new { a = "Hello", b = "World" });
    objs.Add(new { a = "World", b = "Hello" });
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
</head>
<body>
    @Html.BuildTable(objs)
</body>
</html>

看看ModelMetadata。 另请查看 ModelMetadataProvider,甚至可能是 CustomMetadataProvider。

我通常使用这些来呈现完整的编辑器对话框。

ModelMetadata metadata = (ModelMetadata)ViewData.ModelMetadata;
ModelMetadata[] properties = metadata.Properties.Where(pm => pm.ShowForEdit && (pm.IsReadOnly || !ViewData.TemplateInfo.Visited(pm))).ToArray();
foreach (TemplateMetadata prop in properties)
{
    if (!prop.HideSurroundingHtml)
    {
        @Html.Label(prop.PropertyName, prop.DisplayName + ((prop.ModelType != typeof(bool) && prop.IsRequired) ? " *" : ""))
    }
}