我为WebFormViewEngine视图编写了一个非常漂亮的菜单Html帮助器.这个引擎允许你的助手返回void,仍然可以使用:
@Html.Theseus
Run Code Online (Sandbox Code Playgroud)
这对我的助手很有用,因为它可以使用HtmlTextWriter渲染菜单,直接渲染到输出流.
但是,在Razor视图中,Html助手应该返回一个值(通常是MvcHtmlString),这是添加到输出中的值.差异小,后果大.
有一种解决方法,正如GvS指出的那样(参见ASP.NET MVC 2到MVC 3:Razor中的自定义Html助手)如下:
如果帮助程序返回void,请执行以下操作:
@{Html.Theseus;}
Run Code Online (Sandbox Code Playgroud)
(基本上,您只是调用方法,而不是渲染到视图中).
虽然仍然很整洁,但这与@ Html.seus不完全相同.所以...
我的代码很复杂,但效果很好,所以不愿意进行主要编辑,即用另一个编写器替换HtmlTextWriter.一段代码如下:
writer.AddAttribute(HtmlTextWriterAttribute.Href, n.Url);
writer.AddAttribute(HtmlTextWriterAttribute.Title, n.Description);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.WriteEncodedText(n.Title);
writer.RenderEndTag();
// Recursion, if any
// Snip off the recursion at this level if specified by depth
// Use a negative value for depth if you want to render the entire sitemap from the starting node
if ((currentDepth < depth) || (depth < 0))
{
if (hasChildNodes)
{
// Recursive building starts here
// Open new ul …Run Code Online (Sandbox Code Playgroud)