使用 Literal 和 string.Format 生成干净的标记
为了生成干净的标记,我经常求助于使用与此类似的代码:
<asp:Literal ID="ltItem" runat="server">
<li class="{0}"><a href="{1}">{2}</a></li></asp:Literal>
在代码隐藏中:
...
lt.Text = string.Format(lt.Text,
cssClass,
item.Url,
Server.HtmlEncode(item.Caption)
);
一些优点是:
- 干净的 html 标记,没有 ASP.Net WebForm id 等
- 设计人员可以在 aspx 中进行较小的修改,而无需开发人员干预
- 代码是预编译的(而不是使用内联代码或数据绑定语句)
缺点:
- 有点神秘
- 脆弱 - 当在标记中删除参数时, string.Format 会引发异常
因此我的问题:
这是生成干净标记的常见方法吗?有更好的选择吗?数据绑定语法方法更可取吗?
In order to generate clean markup, I often resort to using code similar to this:
<asp:Literal ID="ltItem" runat="server">
<li class="{0}"><a href="{1}">{2}</a></li></asp:Literal>
And in the codebehind:
...
lt.Text = string.Format(lt.Text,
cssClass,
item.Url,
Server.HtmlEncode(item.Caption)
);
Some of the advantages are:
- clean html markup, no ASP.Net WebForm id's etc
- designer can do minor modifications in the aspx without developer intervention
- code is precompiled (as opposed to use inline code or databind statements)
Disadvantages:
- somewhat cryptic
- fragile - when a parameter is removed in the markup, string.Format throws an exception
Therefore my question:
Is this a common way to generate clean markup? Are there better alternatives? Is the databinding syntax approach preferable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来你正在与你的框架作斗争。 ASP.NET Web 表单旨在自动解析客户端 ID,并允许基于属性的 UI 自定义,感觉就像 Windows 表单。这些功能通常会使渲染的 HTML 变得混乱,但由于其明显的好处,结果是可以容忍的。
如果您没有意识到 ASP.NET Web 表单方法的好处并且发现自己正在与 ASP.NET Web 表单方法作斗争,请考虑另一个框架。使用不认同您的价值观和目标的框架是没有意义的。
如果您想完全控制呈现的 HTML,请考虑 ASP.NET MVC。对 HTML 输出的控制是其既定目标之一。此外,它旨在强制实施关注点分离。
如果您对非 Microsoft 框架持开放态度,则有许多可用的框架,包括:
It seems that you're fighting with your framework. ASP.NET web forms were designed to automatically resolve client-side ids and allow property-based UI customization that feels like Windows forms. These features often make a mess of the rendered HTML but the result is tolerated because of the perceived benefits.
If you don't perceive the benefits and find yourself fighting the ASP.NET web forms approach, consider another framework. There's no sense using a framework that doesn't share your values and goals.
If you want total control of your rendered HTML, consider ASP.NET MVC. Control of HTML output is one of its stated goals. In addition, it's designed to enforce separation of concerns.
If you're open to a non-Microsoft framework, there are many available including:
如果我错了请纠正我,但使用 MVC 不会给你预编译代码,不是吗?
我在使用网络表单时也做了同样的事情,但我遇到了一些问题。
Correct me if I am wrong but using MVC won't gives you precompiled code isn't it ?
I do the same when using webforms and I had several issues with it.