开发者

Is it possible to get HTML content between a 'using'

I have created a new HTML helper with a ctor and a Dispose function, and during the time my control is initialised I write some HTML. Like this:

<% using(Html.BeginScript()) { %>
    var jan = "hoi";
    alert(jan);
<% } %>

Is there any way to grab the inner HTML there? Overriding the TextWriter doesn't work:

public class MvcScriptWrapper: IDisposable
{
    private readonly MemoryStream _ms;
    private readonly TextWriter _tw;
    private readonly TextWriter _originalTw;

    public MvcScriptWrapper(HtmlHelper htmlHelper)
    {
        _ms = new MemoryStream();
        _tw = new StreamWriter(_ms);

        _originalTw = htmlHelper.ViewContext.Writer;

        htmlHelper.ViewContext.Writer = _tw;
    }

    public void Dispose()
    {
        _tw.Flush();

        _ms.Seek(0, SeekOrigin.Begin);

        string content;
        using(StreamReader sr = new StreamReader(_ms))
        {
            originalTw.Write(开发者_开发百科sr.ReadToEnd());
        }

        _tw.Dispose();
    }
}


edit To solve these kind of problems I wrote a library called Moth. Besides making your websites fast, it also supports a plugin architecture that hooks into the MVC page flow (MVC 2 and 3) that you can use to apply HTML postprocessing. For an example, see this executor.

Call this function to register your post processor.

MothAction.RegisterExecutor(new YourExecutor());

Setting the InnerWriter works:

// ctor

_originalTw = ((HtmlTextWriter)htmlHelper.ViewContext.Writer).InnerWriter;
((HtmlTextWriter)htmlHelper.ViewContext.Writer).InnerWriter = _tw;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜