asp.net - 如何将转发器绑定(bind)到 List<Person> 以同时更新绑定(bind)的项目? (2种方法)

标签 asp.net data-binding repeater

如果我有一个 List < Person >,其中 person 由类定义

class Person
{
   string Forename
   {
      get;set;
   }
   string Surname
   {
      get; set;
   }
}

我将它绑定(bind)到一个如下所示的 asp 转发器控件:
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="lblForename" runat="server" Text="Forname" AssociatedControlID="txtForename" />
        <asp:TextBox ID="txtForename" runat="server" Text='<%# ((Person)Container.DataItem).Forename %>' />
        <br />
        <asp:Label ID="lblSurname" runat="server" Text="Forname" AssociatedControlID="txtSurname" />
        <asp:TextBox ID="txtSurname" runat="server" Text='<%# ((Person)Container.DataItem).Surname %>' />
        <br />
    </ItemTemplate>
</asp:Repeater>

将用户键入的数据返回到对象中的最佳方法是什么?

我认为数据绑定(bind)的全部意义在于它已经为您有效地处理了,但是当我检查 Repeater1.Items 集合时,没有进行任何更改。我是否必须编写代码来做一些事情
//This is only intended to be pseudo code
for each item in Repeater1.Items
    ((Person)item.DataItem).Forename = item.FindControl("txtForname").Text;
end for

如果是这样,为什么 DataItem 属性总是空的?

附加信息:

我已经在调用代码的效果
this.Repeater1.DataSource =  this.PersonList;
this.Repeater1.DataBind();

我试过使用 Bind("Forename") ,但这似乎不会将 TextBox 中的信息带回对象中,我是否必须手动执行此操作?

最佳答案

简单的答案是Repeater 控件不支持您正在寻找的那种双向数据绑定(bind)。最重要的是,DataItem 属性仅在创建中继器项目期间使用,并且在 ItemDataBound 事件之后,它被设置为空。因此,您不能使用该属性来获取回发后创建特定转发器项目时使用的原始对象(就像您在伪代码中所做的那样)。

您将必须按照您的建议遍历中继器项目(确保在执行任何操作之前检查该项目是否属于 ListItemType.Item 或 AlternatingItem),然后从文本框中提取值并在更新中使用它们。

关于asp.net - 如何将转发器绑定(bind)到 List<Person> 以同时更新绑定(bind)的项目? (2种方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/864149/

相关文章:

asp.net - 在计算模拟器中运行 Azure Web 角色时,web.config 文件在哪里?

asp.net - WebForms 中的强类型容器

javascript - Angular 数据绑定(bind)不适用于 async/await,但它可以用于 promises

c# - 中继器的 ItemDataBound 不会影响某些值

asp.net - 您如何处理 Web 应用程序中的附件?

javascript - 对象文字模式: can't access a data attribute when binding events

c# - 在 MVVM 中绑定(bind)的首选方法,资源文件中的数据模板或只是 View 本身中的 DataContext?

c# - 中继器内部的用户控制

c# - 将通用列表绑定(bind)到转发器 - ASP.NET

c# - 如何从 YAF.NET 论坛标题中删除登录链接?