我们为HtmlHelper添加了两个扩展程序:Content
和Block
。 Content
允许消费者使用剃刀代码创建HtmlStrings
。 Block
尝试允许用户使用标题和内容部分创建html块。我试图理解为什么razorContent
参数不能在using块内编译。我想保留使用块的使用,因为我觉得它看起来很干净。有没有办法在不将Block
上的第二个参数更改为HtmlString
的情况下进行编译?
剃刀:
@* uses of Html.Content compiles as expected *@
@Html.Content(@<span>foo</span>)
@{
IHtmlString htmlString = Html.Content(@<span>bar</span>);
}
@htmlString
@* "@<span>header</span>" does not compile
*
* expected markup:
* <div class="header">
* <span>header</span>
* </div>
* <div class="content>
* <span>content</span>
* </div>
*@
@using (Html.Block(@<span>header</span>))
{
<span>content</span>
}
扩展:
public static class HtmlHelperExtensions
{
public static IHtmlString Content(this HtmlHelper htmlHelper, Func<object, HelperResult> razorContent)
{
var content = razorContent(null);
return content;
}
public static IDisposable Block(this HtmlHelper htmlHelper, Func<object, HelperResult> razorContent)
{
var content = razorContent(null);
return new MyHtmlBlock(htmlHelper, content);
}
}
MyHtmlBlock:
public class MyHtmlBlock : IDisposable
{
private readonly TextWriter _writer;
private readonly TagBuilder _contentTag;
public MyHtmlBlock(HtmlHelper htmlHelper, IHtmlString header)
{
this._writer = htmlHelper.ViewContext.Writer;
var headerTag = new TagBuilder("div");
headerTag.AddCssClass("header");
headerTag.InnerHtml = header.ToHtmlString();
this._contentTag = new TagBuilder("div");
this._contentTag.AddCssClass("content");
this._writer.Write(headerTag);
this._writer.Write(this._contentTag.ToString(TagRenderMode.StartTag));
}
public void Dispose()
{
this._writer.Write(this._contentTag.ToString(TagRenderMode.EndTag));
}
}