干净的解决方案:填充;通过嵌入式代码还是代码隐藏?
假设我必须使用不使用 MVC 的项目中的 Dictionary
数据填充无序列表。我确信 ASP.Net 爱好者会告诉我从代码隐藏中填充所有内容。 但是……我应该吗?
通过嵌入代码:
<ul>
<% foreach (KeyValuePair<string, string> item in MyDictonary) { %>
<li><%= item.Key %>: <strong><%= item.Value %></strong></li>
<% } %>
</ul>
我同意它不是很干净,但替代方案要糟糕得多,因为我必须直接从我的方法编写 HTML 标记:
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();
}
那么,为什么我应该使用代码隐藏来填充我的所有控件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于此用例,在代码隐藏中执行此操作没有特别的价值。
我宁愿使用标记版本而不是后面的代码,正如您发布的那样,但我可能会简单地在
Repeater
,因为这将是最干净的解决方案。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.您还可以考虑使用中继器控件 http://msdn.microsoft.com/en-我们/杂志/cc163780.aspx。
You can also consider using repeater controls http://msdn.microsoft.com/en-us/magazine/cc163780.aspx.
对于维护此功能的人来说,哪一个不那么令人惊讶(例如,如果他们想要更改标记)?
代码隐藏可能不是他们首先要查看的地方。
Which is less surprising for someone maintaining this (e.g. if they want to change the markup)?
Code-behind is probably not the first place they would look.