【问题标题】:User control property set in code front is null in OnPreRender代码前面设置的用户控件属性在 OnPreRender 中为空
【发布时间】:2018-05-04 14:58:13
【问题描述】:

TestPage 有一个属性Items 我想传递给我的自定义用户控件Control。我喜欢在代码前端设置属性的语法,所以 TestPage.aspx 看起来像这样...

主页:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" %>

<%@ Register Src="~/Control.ascx" TagPrefix="custom" TagName="Control" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Test Page</title></head>
<body>

    <custom:Control ID="TestControl" Items='<%# Items %>' runat="server" />

</body>
</html>

TestPage 的代码隐藏具有 Items 属性和一个简单的 getter:

using System;
using System.Collections.Generic;
using System.Web.UI;

public partial class TestPage : Page
{
    protected List<string> Items = new List<string>() { "Hello", "world!", };
}

控制:

我的自定义用户控件有一个转发器来呈现Items 中的值。

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Control.ascx.cs" Inherits="Control" %>

<asp:Repeater ID="Repeater" ItemType="System.string" runat="server">
    <ItemTemplate>
        <p><%# Item %></p>
    </ItemTemplate>
</asp:Repeater>

控件的代码隐藏公开了公共Items 属性并将其绑定到Repeater

using System;
using System.Collections.Generic;
using System.Web.UI;

public partial class Control : UserControl
{
    public List<string> Items { get; set; }

    protected override void OnPreRender(EventArgs e)
    {
        Repeater.DataSource = Items;
        Repeater.DataBind();
    }
}

问题:

呈现的页面是空的,因为OnPreRender中的Control.Items == null

如果我在TestPage.Page_Load 中设置TestControl.Items = ItemsControl.Items 将填充在Control.OnPreRender 中。

这行得通,但我很迂腐。在TestPage的代码前面设置Items时是否可以绑定转发器?

【问题讨论】:

  • 你在任何地方都调用 TestControl.DataBind() 吗? &lt;%# ... %&gt; 语法仅在您在控件上调用 DataBind 时设置属性。
  • @MichaelLiu 那是票。我习惯于仅在内置控件的上下文中考虑数据绑定。出于某种原因,没有发生在自定义控件中执行此操作。放弃一个答案,我会接受它。

标签: c# asp.net


【解决方案1】:

Items='&lt;%# Items %&gt;' 中的数据绑定赋值

<custom:Control ID="TestControl" Items='<%# Items %>' runat="server" />

只有在调用控件的DataBind方法时才会执行:

TestControl.DataBind();

如果您的页面有其他数据绑定表达式,您也可以调用Page.DataBind(),它会递归绑定所有子控件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    相关资源
    最近更新 更多