将值绑定到用户控件,但返回null

本文关键字:返回 null 控件 用户 绑定 | 更新日期: 2023-09-27 18:21:41

在我的webfrom中,我有一个中继器,它从webservice获取一些项目信息,输出是list。

<asp:Repeater ID="Repeater1" runat="server">
 <ItemTemplate>
          <uc1:ItemDetailsUserControl runat="server" ID="ItemDetailsUserControl1"  HotelCode='Eval("Item.Code")' CityCode='<%#Eval("City.Code")%>'/>
</ItemTemplate>

为了获得每个项目的详细信息,我在我的用户控制中有这个定义——ItemDetailsUserControl,

    public string ItemCode { set; get; }
    public string CityCode { set; get; }

这是用户控制代码,

    protected void Page_Load(object sender, EventArgs e)
    {
       //do some stuff 
       response.write(ItemCode); //null
       response.write(CityCode); //null
    }

问题在于中继器中的绑定。当我得到eval时,它只是返回值,但当我将其作为属性传递时,它返回null值。

将值绑定到用户控件,但返回null

您每年都会获得属性的值-在Page_Load事件中,中继器控件尚未填充数据。一个可能的解决方案是将代码移动到Page_PreRender事件。

检索和使用resp的示例。更改绑定到中继器的数据可以在这里找到:http://runnable.com/UjMj269qAWwQAAB3/asp-net-how-to-use-repeater.

为了在给定的例子中匹配您的情况,请将此代码添加到现有代码中:

protected void Page_PreRender(object sender, EventArgs e)
{
    if (lstEmployees.Count > 0)
    {
      lstEmployees.First().FirstName = "Test";
      rptEmployees.DataSource = lstEmployees;
     //You need to rebind the repeater
      rptEmployees.DataBind();
    }
}
private List<Employee> lstEmployees = new List<Employee>();

输出:http://runnable.com/VBQHUzNw-OxoDUWX/output.