Suppose I have to populate an unordered list with data from a Dictionary
in a project not using MVC. I'm sure ASP.Net lovers will tell me to populate everything from code-behind.
But... should I?
Via embedded code:
<ul>
<% foreach (KeyValuePair<string, string> item in MyDictonary) { %>
<li><%= item.Key %>: <strong><%= item.Value %></strong></li>
<% } %>
</ul>
I agree it is not a lot clean, but the alternative is a lot worse as I got to write HTML markup directly from my method:
public void writeMyDictionary() {
StringBuilder sb = new StringBuilder();
sb.Append("<ul>");
foreach (KeyValuePair<string, string> item in MyDictonary) {
sb.AppendFormat("<li>{0}: <strong>{1}</strong></li>", item.Key, item.Value);
}
sb.Append("</ul>");
MyControl.Text = sb.ToString();
}
So, why should I use code-behind to populate all my controls?
For this use case, there is no particular value to doing it in code behind.
I would rather use the markup version instead of the code behind, as you have posted them, but chances are I would simply go with data binding on a Repeater
, as it would be the cleanest solution.