Access to stream of ViewContext's writer

1.3k Views Asked by At

I'm writing an html helper extension for MVC5. I need to access the ViewContext's stream to edit it. (like a textreader)

htmlHelper.ViewContext.Writer.Write("<div>");

Is there any way to access the stream; so that I can manipulate or add some html code above the last "div" tag in the example ?

I was not able to find any clue about at where I can find the stream that textwriter writes to?

1

There are 1 best solutions below

0
Bron Davies On

It depends on what view engine you are using but if you write an html helper, it will be a lot easier. See Creating Custom HTML Helpers

Simple html helpers can be written like this:

@helper CustomDiv(var param1, var param2){
    Write("something to html encode & stuff");
    WriteLiteral("<div>something that is html</div>");
}

In Razor, You can also just call @Write() and it will encode the string to HTML. If you need a TextWriter, reference Context.Response.Output but this will not allow you to manipulate the HTML inline like an HtmlHelper does - it's intended more for overriding the normal handler.

or just the Output property of WebPageBase which is also a TextWriter