好的,这就是我要做的......给这个剃刀代码
@using(Html.WriteLater())
{
output line one
}
actual first line
@using(Html.WriteLater())
{
output line two
}
actual second line
@HTML.WriteNow();
我想要这个输出:
actual first line
actual second line
output line one
output line two
有时在视图中将代码块逻辑分组在一起很好,但最终输出需要以不同方式进行组织。我尝试在我的帮助程序逻辑中使用不同的ViewContext,但它不起作用:
public static WriteLaterContainer WriteLater( this HtmlHelper htmlHelper )
{
ViewContext vc = new ViewContext();
return new WriteLaterContainer( vc );
}
答案 0 :(得分:3)
不知道你为什么要重新发明轮子而不是使用标准方法,如局部,部分,助手......但我想你可能有一些原因。所以不完全是你所展示的语法,但你可以通过使用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