简体   繁体   中英

ASP.NET: Page HTML head rendering

I've been trying to figure out the best way to custom render the <head> element of a page to get rid of the extra line breaks which is caused by <head runat="server"> , so its properly formatted.

So far the only thing i've found which works is the following:

    protected override void Render(HtmlTextWriter writer)
    {
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlTextWriter);
        htmlTextWriter.Close();
        string html = stringWriter.ToString();
        string newHTML = html.Replace("<title>\r\n\t", "<title>")
                             .Replace("\r\n</title>", "</title>")
                             .Replace("</head>", "\n</head>");

        writer.Write(newHTML);
    }

Now i have 2 questions:

  1. How does the above code affect the performance (so is this viable in a production environment)?
  2. Is there a better way to do this, for example a method which i can override to just custom render the <head> ?

Oh yeah ASP.NET MVC is not an option.

EDIT:

Im asking this with regards to SEO and just little bit perfectionism.

From my experience, using ASP.NET Forms implies an irrevocable surrender of control over your HTML output. It is better to accept the following:

  • Microsoft form controls will sometimes use depreciated or flat-out wrong HTML.
  • The Viewstate tag will always be there, even when ViewState is disabled at the page or site level. Apparently, there needs to be a ViewState to tell ASP.NET that there isn't a view state.
  • You are not in control of form elements. There will be one form element per page, and it belongs to ASP.NET.
  • JavaScript will be used to perform even rudimentary tasks. The JavaScript will be unreadable, directly embedded in your page, and at least 50% of it will be extraneous.
  • You will not be able to create page fragments, unless you do it through a web service and a lot of kludge. Each .aspx page will have <html> <head> and almost always <form> tags.

If you want fine control over your page output, using MVC or another framework is all but mandatory. Even classic ASP will work, but not ASP.NET Forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM