c# - DynamicData - 如何在 Children.ascx.cs FieldTemplate 中显示 child 数量?

标签 c# asp.net dynamic-data asp.net-dynamic-data metamodel

MS DynamicData 的 Children.ascx.cs 文件有一个 Page_Load 方法,它返回一个超链接,上面写着“View Children”。我想将 child 的数量附加到超链接文本的末尾。以下是我的尝试。如何让超链接显示“查看子项 - # 条目”?

protected void Page_Load(object sender, EventArgs e)
{
    HyperLink1.Text = "View " + ChildrenColumn.ChildTable.DisplayName;

    //The following code gives the total entries.
    //How do I get the number of children only?
    //int entries = 0;
    //foreach (var entry in ChildrenColumn.ChildTable.GetQuery()) { entries++; }
    //string entryText = (entries == 1) ? "entry" : "entries";
    //HyperLink1.Text= HyperLink1.Text + " " + entries + " " + entryText;
}

最佳答案

其实并没有那么难。您可以将以下方法添加到您的 Children.ascx.cs 文件中:

    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);

        object entity;
        ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
        if (rowDescriptor != null)
        {
            // Get the real entity from the wrapper
            entity = rowDescriptor.GetPropertyOwner(null);
        }
        else
        {
            entity = Row;
        }

        // Get the collection and make sure it's loaded
        RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;
        if (entityCollection == null)
        {
            throw new InvalidOperationException(String.Format("The Children template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
        }
        if (!entityCollection.IsLoaded)
        {
            entityCollection.Load();
        }

        int count = 0;
        var enumerator = entityCollection.GetEnumerator();
        while (enumerator.MoveNext())
            count++;

        HyperLink1.Text += " (" + count + ")";
    }

关于c# - DynamicData - 如何在 Children.ascx.cs FieldTemplate 中显示 child 数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883212/

相关文章:

c#,MSBuild Bootstrapper with wix,如何下载.net framework 3.5 SP1?

c# - 队列中有新项目时如何出队

c# - 将值从 ASP.NET 页面发布到 C#

asp.net - 如何让服务器端ASP页面在客户端浏览器中显示弹出消息?

c# - 如何在 ASP.NET 中递归查找控件

c# - Blazor InputText、HTML Input 和直接从 C# 代码分配之间的差异

c# - 为什么 MtpDevice.ImportFile 总是失败?

c# - 在 ITextSharp 免费许可证下动态创建 .pdf

ms-access - 当字段名称是动态时vba制作表格

mysql - 批评我的 MySQL 数据库设计无限动态字段