Qual a melhor forma de preencher uma tabela HTML no ASP.NET?
Pergunta
Isto é o que eu tenho.Funciona.Mas existe uma maneira mais simples ou melhor?
Página ASPX…
<asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Código ASPX.VB por trás…
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return " "
Else
Return s
End If
End Function
Solução
@Geoff
Esse tipo de instrução Eval foi adicionada na versão 2.0, mas se o desempenho for importante, Eval deve ser evitado, pois usa Reflexão.
O repetidor é uma boa maneira de fazer isso, embora possa ser mais rápido gerar a tabela em código:
Página ASPX:
<table class="report" id="bookTable" runat="server">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</table>
Código por trás:
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostback Then
BuildTable()
End If
End Sub
Private Sub BuildTable()
Dim db As New BookstoreDataContext
Dim bookCollection = from b in db.Books _
Order By b.Published _
Select b
Dim row As HtmlTableRow
Dim cell As HtmlTableCell
For Each book As Books In bookCollection
row = New HtmlTableRow()
cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = Format(b.Price, "c") }
row.Controls.Add(cell)
bookTable.Controls.Add(row)
Next
Acho que depende de quão importante a velocidade é para você.Para simplificar, acho que escolheria o Repetidor.
Outras dicas
O Exibição de lista o controle introduzido com o framework 3.5 pode ser uma solução um pouco melhor.Sua marcação ficaria assim:
<asp:ListView runat="server" ID="ListView1"
DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id="table1" runat="server" >
<tr runat="server" id="itemPlaceholder" ></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server>
<td runat="server">
<asp:Label ID="NameLabel" runat="server"
Text='<%#Eval("Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
No .Net 3.0+ você pode substituir seu ItemDataBound pelo asp:Literal fazendo algo assim:
<ItemTemplate>
<tr>
<td><%# Eval("published") %></td>
...
onde "publicado" é o nome de um campo nos dados que você vinculou ao repetidor
Editar:@Alassek:Acho que o impacto da reflexão no desempenho costuma ser superestimado.Obviamente, você precisa avaliar o desempenho do seu aplicativo, mas o acerto do Eval provavelmente é medido em milissegundos.A menos que seu aplicativo esteja atendendo a muitos acessos simultâneos, isso provavelmente não é um problema, e a simplicidade do código usando Eval, além de ser uma boa separação da apresentação, o torna uma boa solução.
É para isso que serve o GridView.
<asp:GridView runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField HeaderText="Published" DataField="Published" />
<asp:BoundField HeaderText="Author" DataField="Author" />
</Columns>
</asp:GridView>
Eu usaria um GridView (ou DataGrid, se você estiver usando uma versão mais antiga do ASP.NET).
<asp:GridView ID="gvBooks" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Published" DataField="Published" />
<asp:BoundField HeaderText="Title" DataField="Title" />
<asp:BoundField HeaderText="Author" DataField="Author" />
<asp:BoundField HeaderText="Price" DataField="Price" />
</Columns>
</asp:GridView>
Com algum code-behind:
Private Sub gvBooksRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBooks.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
''' Your code here '''
End Select
End Sub
Você pode vinculá-lo de maneira semelhante.O evento RowDataBound é o que você precisa.
Concordo com Geoff, a única vez que usamos Literals
é se quisermos fazer algo diferente com os dados.
Por exemplo, podemos querer um DueDate
campo para dizer "Hoje" ou "Ontem" em vez da data real.
Alassek escreveu:
…gerar a tabela em código…
Eu gosto da aparência disso!Parece MUITO menos provável produzir uma exceção em tempo de execução devido a um erro de digitação ou alteração do nome do campo.
Se você não precisa de recursos de edição manipulados pelo ASP.NET, eu faria ficar longe do DataGrid e do GridView ...eles providenciam inchaço desnecessário.