我正在捕捉部分MVC视图:
<% using(Html.BeginScriptWrapper()) { %>
<script type="text/javascript">
alert("Test : <%: DateTime.Now %>");
</script>
<% } %>
HtmlHelper
扩展程序的代码:
public static class HelperScriptWrapper
{
public static IDisposable BeginScriptWrapper(this HtmlHelper anHtml)
{
return new ScriptWrapper(anHtml);
}
class ScriptWrapper : IDisposable
{
private HtmlHelper fHtml;
private TextWriter fOldWriter;
private StringWriter fNewWriter;
private TextWriter ReplaceInnerWriter(TextWriter aReplacement)
{
TextWriter writer = fHtml.ViewContext.HttpContext.Response.Output;
PropertyInfo propInfo = writer.GetType().GetProperty("InnerWriter",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
TextWriter oldWriter = propInfo.GetValue(writer, null) as TextWriter;
propInfo.SetValue(writer, aReplacement, null);
return oldWriter;
}
public ScriptWrapper(HtmlHelper anHtml)
{
fHtml = anHtml;
fNewWriter = new StringWriter();
fOldWriter = ReplaceInnerWriter(fNewWriter);
}
public void Dispose()
{
ReplaceInnerWriter(fOldWriter);
string result = fNewWriter.GetStringBuilder().ToString();
// store result to use later
}
}
}
反射用于将InnerWriter
替换为我的StringWriter
。
是否有正确的(ASP.NET MVC by-design)方法可以在没有反射的情况下执行此操作?
这是为了在视图中间重定向到Response.Output
的内容。