Chris Arnold
Chris Arnold

Reputation: 5753

Controlling Output Indentation in ASP.Net MVC

My colleague is extremely 'hot' on properly formatted and indented html being delivered to the client browser. This is so that the page source is easily readable by a human.

Firstly, if I have a partial view that is used in a number of different areas in my site, should the rendering engine be automatically formatting the indentations for me (ala setting the Formatting property on an XmlTextWriter)?

Secondly, my colleague has created a number of HtmlHelper extension methods for writing to the response. These all require a CurrentIndent parameter to be passed to them. This smells wrong to me.

Can anyone help with this?

Upvotes: 2

Views: 2786

Answers (4)

G-Wiz
G-Wiz

Reputation: 7426

Rather than waste time implementing a proper indenting solution which would affect all HTTP requests (thus adding CPU and bandwidth overhead), just suggest to your colleague that he use an HTML beautifier. That way the one person that cares about it is the one person that pays the cost of it.

This Firefox plugin is an HTML validator that also includes a beautification function. See the documentation here.

Upvotes: 2

Chris Fulstow
Chris Fulstow

Reputation: 41902

This sounds difficult to maintain. If someone removed an outer element from the HTML, would anyone bother to update the CurrentIndent values in the code? These days most developers usually view their HTML through Firebug anyway, which formats the markup automatically with indentation.

If you really want to post-process HTML through a formatting filter then try a .NET port of HTML Tidy.

Upvotes: 6

Çağdaş Tekin
Çağdaş Tekin

Reputation: 16661

Even if for some crazy reason it HAS TO be indented "properly", it shouldn't be done the way your colleague suggests.

An HttpModule attached to ReleaseRequestState event of the HttpApplication object should do the trick. And of course, you're going to need to come up with a filter that handles this indenting.

public class IndentingModule: IHttpModule {

    public void Dispose() {
    }

    public void Init(HttpApplication context) {
        context.ReleaseRequestState += 
            new EventHandler(context_ReleaseRequestState);
    }

    void context_ReleaseRequestState(object sender, EventArgs e) {
        HttpApplication app = (HttpApplication)sender;
        app.Response.Filter = new IndentingFilter(app.Response.Filter)
    }
}

Upvotes: 3

Anton Gogolev
Anton Gogolev

Reputation: 115867

Browsers absolutely don't care how beautiful the HTML indentation is. What's even more, deeply nested (and thus heavily indented) HTML adds a slight overhead to the page (in terms of bytes to download). Granted, you can always compress response and well-indented HTML is nicer to support.

Upvotes: 3

Related Questions