已经有很多关于 ASP.NET MVC 的视图引擎的讨论,以及对带有 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 集合中。
这有什么明显的问题或限制吗?