Controlling Output Indentation in ASP.Net MVC

无人久伴 提交于 2019-12-02 02:52:39

问题


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?


回答1:


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.




回答2:


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.




回答3:


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)
    }
}



回答4:


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.



来源:https://stackoverflow.com/questions/1593057/controlling-output-indentation-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!