【发布时间】:2009-05-06 08:20:28
【问题描述】:
关于 ASP.NET MVC 的 View-engines 进行了很多讨论,并且对带有 for 循环的内联“标签汤”之类的东西提出了一些批评。
替代或补充是使用 HTML 助手,它们只是内联方法调用。
当我今天查看 ASP.NET MVC 的 HTML 助手时,他们正在使用一个名为 TagBuilder 的类。
我的建议是使用 LINQ to XML 来获得强类型和正确格式的 (X)HTML:
XDocument output = new XDocument();
XElement root = new XElement("div",
new XAttribute("class", "root_item"));
XElement iconImage = new XElement("img",
new XAttribute("src", ResolveUrl("~/image.gif")),
new XAttribute("alt", "This is an image"));
XElement link = new XElement("a",
new XAttribute("class", "link"),
new XAttribute("href", "http://google.com"),
new XText("Link to Google"));
root.Add(link);
root.Add(iconImage);
output.Add(root);
我喜欢它,因为它就像 WebForms 中的强类型控件,您可以在其中新建一个 Button 并将其添加到另一个控件的 Control-collection。
这有什么明显的问题或限制吗?
【问题讨论】:
-
我个人不是 TagBuilder 的粉丝,并且在大多数情况下都求助于构建我自己的,实际上只不过是一个 string.Format()。我喜欢你的方法,但你为什么不想使用 TagBuilder?你可以用 TagBuilder 做同样的事情。
标签: asp.net asp.net-mvc linq-to-xml html-helper