I've inherited an ASP.net web application where the previous developer used the convention of having an ASP.net GridView for each table that displays data to the user, even if it is not a page that will take advantage of paging or viewstate in any way.
I've become a bit fed up with some of the limitationsand cruft associated with GridView and I'm thinking of rolling my own on some pages.
My questions: "Is this a good idea?" "What are the pitfalls?"
My code looks like this:
<table>
<%=EquipmentTableHeadingsRowHTML() %>
<%foreach(Entry entry in TableEntries)
{ %>
<%=WriteTableRowForEntry(entry) %>
<% } %>
</table>
public string WriteTableRo开发者_如何学CwForEntry(Entry entry)
{
StringBuilder sb = new StringBuilder();
sb.Append("<tr><td>");
sb.Append(entry.Description);
sb.Append("</td><td>");
sb.Append(entry.NumberRequired);
sb.Append("</td><td>");
sb.Append(entry.NumberCurrent);
sb.Append("</td><td>");
sb.Append(entry.NumberRequired);
sb.Append("</td><td>");
sb.Append(entry.CostEach);
sb.Append("</td><td>");
sb.Append("TOTAL COST");
sb.Append("</td></tr>");
return sb.ToString();
}
That's funny.. I just inherited code written by a third party and was going to send it back to them telling them to use a Repeater or a List, but then I realized that they were using a couple of java script frameworks that rely on predictable IDs. Older versions of the .NET framework don't allow much flexibility in specifying the IDs of server controls. The 3rd party developer created htmlElements in a loop in code-behind to compensate, so she had a good reason in this case.
The short answer, based on this new experience is that generating tables (or other repeatable content) in code-behind is, in my opinion, not a good thing. It's more difficult to read the code, and defeats the purpose of having DataBound controls, so it's a poor use of the platform, BUT if there is a good reason, then an exception can be made.
In THIS code example, I think it's a bad thing.
No. This builds up your code behind with presentation. You generally shouldn't have your code behinds generate html.
A repeater might be a better option for you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx
Use the ListView and you'll end up with cleaner markup ;-)
精彩评论