我正在使用带有 ASPX 视图引擎的 ASP.NET MVC 3.0。
我目前有一种方法,它使用正则表达式来匹配文本中的某些单词并相应地突出显示它们。到目前为止,我正在使用它来处理从平面文件中读取的大量文本。我在这篇文章中试图实现的最终目标是能够捕获视图的内容部分,并使用相同的方法处理它们。
这是我目前正在尝试实现此目标的基本示例:
<h2>This is a Test</h2>
<p>Line before capture</p>
<% using (Html.CaptureContent())
{ %>
<p>this line should be in capitals</p>
<%} %>
<p>Line after capture</p>
Html.CaptureContent:
public static ContentCapture CaptureContent(this HtmlHelper html)
{
return new ContentCapture(html.ViewContext.HttpContext);
}
内容捕获:
public class ContentCapture : IDisposable
{
private HttpContextBase Context { get; set; }
private TextWriter OriginalOutput { get; set; }
private StringWriter CaptureOutput { get; set; }
public ContentCapture(HttpContextBase context)
{
CaptureOutput = new StringWriter();
//save the default writer in private property
OriginalOutput = context.Response.Output;
Context = context;
Context.Response.Output = CaptureOutput;
}
public void Dispose()
{
string processedContent = CaptureOutput.ToString().ToUpper();
Context.Response.Output = OriginalOutput;
Context.Response.Output.Write(processedContent);
}
}
当我运行它时,输出与视图中的标签完全相同,没有对 using 块中的 <p> 标签应用任何处理。我尝试了几种变体,但没有成功。我猜我对如何呈现视图做出了错误的假设,因为在 dispose 方法中放置了一个断点,这表明我没有向 StringWriter 对象写入任何内容。
有谁知道我可以达到预期效果的方法?我不希望求助于帮助器返回硬编码字符串中的所有内容部分。