Hellraiser
Hellraiser

Reputation: 609

Overriding RazorView's RenderView method

I'm working on a class which should scan the whole html view, parse it, and replace some elements inside the DOM. For that I decided to create a custom RazorView and override the RenderView method: I call the base.RenderView to get the writer populated, then get the string in it, parse it, and eventually change all I need.

But after that I should put the new string back to the writer for it to be rendered. And I can't get where to put it. Any clues?

Should I overwrite Render method instead?

Upvotes: 1

Views: 957

Answers (1)

Hellraiser
Hellraiser

Reputation: 609

I've found the solution:

    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
    {
        //Create a temporary writer
        TextWriter w = new StringWriter();

        //And call the base method with it
        base.RenderView(viewContext,w,instance);

        //Now I get the HTML from the temp writer
        var html = w.ToString();

        //Do my things and change the HTML

        //And finally write the changes back to the main writer
        writer.Write(html);
    }

To be honest it's a little more complex than this, but this is the base I started from.

Upvotes: 2

Related Questions