简体   繁体   中英

Add doctype to an aspx page dynamically from ascx.cs

Is it possible to add <!DOCTYPE HTML> to an aspx page from the code behind file of a ascx page? Adding doctype to the master page is not an option because it'll wreck the rest of our sharepoint sites.

I've tried to override the render method:

protected override void Render(HtmlTextWriter writer)
{
    StringBuilder sb = new StringBuilder("<!DOCTYPE HTML>");
    HtmlTextWriter textWriter = new HtmlTextWriter(new System.IO.StringWriter(sb));
    //base.Render(writer);
    base.Render(textWriter);
    writer.Write(sb.ToString());  
}

but apparently it doesn't help.

For me it worked this way:

First I added a literal on top of the page, first line, outside the <Form runat="server" :

<asp:Literal runat="server" ID="litHTMLSchema"></asp:Literal>

Then from code-behind:

// HTML 5
litHTMLSchema.Text = @"<!DOCTYPE html>" + Environment.NewLine + @"<html>";

I don't think this is the best approach, but it works without any issues.

Since you are using sharepoint, you could create a custom webcontrol in code in a WSP Package Farm Solution.

  1. Create a class Called DynamicDocTypeControl

     public class DynamicDocTypeControl : System.Web.UI.WebControl *(check namespace for typos) { override Render(...) { //add some conditional logic here for your dynamicness... writer.Write("<!DOCTYPE HTML>"); } } 
  2. Add an empty sharepoint element to your project and go to the properties window and use the safe control section in the property window to register your control as a safe control.

  3. Build/Package the wsp and deploy it to the farm.

Then edit your master page in sharepoint designer and drop your control on it where the doctype should be rendered.

Putting it in the master page won't wreck your sites because you can make your render logic not render anything if it's not on an allowed page.

Just have some code on your aspx page that sets an HttpContext.Current.Item... value that the doctype control looks for to determine if it should render. As long as your aspx page sets the config flag before Render is called it will be there when render fires on the doc type control.

eg

<@ Register TagPrefix="XYZ" Namespace="XYZ.Controls" Assembly="XYZ... (include fully qualified assembly name)" />


<XYZ:DynamicDocTypeControl />

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