干净的解决方案:填充
    ;通过嵌入式代码还是代码隐藏?

发布于 2024-12-14 10:42:36 字数 838 浏览 5 评论 0原文

假设我必须使用不使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乞讨 2024-12-21 10:42:36

对于此用例,在代码隐藏中执行此操作没有特别的价值。

我宁愿使用标记版本而不是后面的代码,正如您发布的那样,但我可能会简单地在 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.

私藏温柔 2024-12-21 10:42:36

您还可以考虑使用中继器控件 http://msdn.microsoft.com/en-我们/杂志/cc163780.aspx

You can also consider using repeater controls http://msdn.microsoft.com/en-us/magazine/cc163780.aspx.

勿挽旧人 2024-12-21 10:42:36

对于维护此功能的人来说,哪一个不那么令人惊讶(例如,如果他们想要更改标记)?

代码隐藏可能不是他们首先要查看的地方。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文