不知道你为什么要重新发明轮子而不是使用标准方法,如部分、部分、助手……但我想你可能有一些原因。所以不完全是你展示的语法,但你可以通过使用 2 个助手的结合来获得类似的结果:
public static class HtmlExtensions
{
private const string QueueKey = "_output_queue_";
public static IHtmlString WriteLater(this HtmlHelper htmlHelper, Func<object, HelperResult> action)
{
var queue = htmlHelper.ViewContext.HttpContext.Items[QueueKey] as Queue<Func<object, HelperResult>>;
if (queue == null)
{
queue = new Queue<Func<object, HelperResult>>();
htmlHelper.ViewContext.HttpContext.Items[QueueKey] = queue;
}
queue.Enqueue(action);
return MvcHtmlString.Empty;
}
public static IHtmlString WriteNow(this HtmlHelper htmlHelper)
{
var queue = htmlHelper.ViewContext.HttpContext.Items[QueueKey] as Queue<Func<object, HelperResult>>;
if (queue == null)
{
return MvcHtmlString.Empty;
}
var writer = htmlHelper.ViewContext.Writer;
foreach (var item in queue)
{
item(null).WriteTo(writer);
}
return MvcHtmlString.Empty;
}
}
可以这样使用:
@Html.WriteLater(@<div>output line one</div>)
<div>actual first line</div>
@Html.WriteLater(@<div>output line two</div>)
<div>actual second line</div>
@Html.WriteNow()
输出将是预期的:
actual first line
actual second line
output line one
output line two