DynamicData - 如何在Children.ascx.cs FieldTemplate中显示子计数?

时间:2012-01-16 16:40:37

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

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

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;
}

4 个答案:

答案 0 :(得分:3)

实际上并不难。您可以将以下方法添加到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 + ")";
    }

答案 1 :(得分:1)

好吧,HyperLink1.Text =“SomeString”应该使你的超链接文本成为“SomeString”

HyperLink1.Text = "View Children -"+numEntries+" entries";

应该让超链接说出你想说的内容,只要当时numEntries是正确的数字,至少它在我的机器上是这样的..

您当前的尝试结果是什么?

答案 2 :(得分:1)

我在这里找到了一个潜在的解决方案'FieldTemplates:Children.ascx:显示计数'http://forums.asp.net/t/1466373.aspx/1

答案 3 :(得分:0)

我有一个非常简单的使用动态的通用解决方案:

重写Childrex.aspx.cs中的OnDataBiding方法,并使用以下代码获取子实体的数量。

// get the field using dynamic
dynamic dynamicField = FieldValue;

// get the count property (this is a valid property for an EnitySet)
int count = dynamicField.Count;
相关问题