我对 ASP.NET 还很陌生,最近我发现了中继器。有些人使用它们,其他人不使用,我不确定哪种解决方案是最佳实践。
根据我的经验,它使简单的操作(显示列表)变得简单,但是一旦你想做更复杂的事情,复杂性就会爆炸,逻辑明智。
也许只是我和我对这个概念的理解很差(这很有可能),所以这是我想要做什么和我的问题的一个例子:
问题:我想显示位于文件夹中的文件列表。
解决方案:
String fileDirectory = Server.MapPath("/public/uploaded_files/");
String[] files = Directory.GetFiles(fileDirectory);
repFiles.DataSource = files;
repFiles.DataBind();
和
<asp:Repeater ID="repFiles" runat="server" OnItemCommand="repFiles_ItemCommand" >
<ItemTemplate>
<a href="/public/uploaded_files/<%# System.IO.Path.GetFileName((string)Container.DataItem) %>" target="_blank">View in a new window</a>
<br />
</ItemTemplate>
</asp:Repeater>
这工作正常。
新问题:我希望能够删除这些文件。
解决方案:我在项目模板中添加了一个删除链接:
<asp:LinkButton ID="lbFileDelete" runat="server" Text="delete" CommandName="delete" />
我抓住了这个事件:
protected void repFiles_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "delete")
{
// ... blah
}
}
……然后呢?知道 e.Item.DataItem 为空(我运行了调试器),我如何获取要从此处删除的文件路径。
当我可以使用循环来完成同样的事情时,我是否只是浪费了使用中继器的时间,这同样简单,只是 - 可能 - 不那么优雅?
与其他解决方案相比,使用中继器的真正优势是什么?