关于 ASP.NET MVC 的 View 引擎有很多讨论,并且对带有 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 集合中。
这是否存在任何明显的问题或限制?
最佳答案
这是个好主意!我发现它的唯一问题是 C# 的使用。 ;) VB.NET 通过其 XML 文字功能对生成 XML 提供了更好的支持。
您在问题中列出的代码可以在 VB.NET 中这样编写。 (添加文本“这是一个链接”,因为您的示例在 a
元素中不包含任何文本。)
Dim root = <div class="root_item">
<img src=<%= ResolveUrl("~/image.gif") %> alt="This is an image"/>
<a class="link" href="http://google.com">This is a link</a>
</div>
还有<%= ... %>
标签,但在编译时检查它们的有效性。如果此代码是返回类型 XElement 的函数的返回值,则该 Xhtml 代码段可以在网站的其他位置重用。
我在 CodePlex 上有一个项目,它使用 VB.NET XML Literals 作为自定义 ASP.NET MVC View 引擎,地址为 http://vbmvc.codeplex.com 。它基于 Dmitry Robsman 的代码,他是 Microsoft 的 ASP.NET 产品部门经理。 View 是 VB.NET 类,母版页是基类。您新建部分 View 类,而不是通过名称字符串引用它们,因此这也是额外的编译时检查。有一个返回 XElement 的 XhtmlHelper 类,而不是返回字符串的 HtmlHelper 类,其工作方式与您建议的类似。
关于ASP.NET MVC : Using LINQ to XML to render (X)HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/828560/