Is there any way to create a handler that changes the head tag content
real time?
You can use HtmlGenericControl Server Control for this purpose.
HtmlGenericControl Server Control
Creates a server-side control that maps to an HTML element not represented by a specific .NET Framework class, such as <body> and <div>.
Try Below one.
var h1 = new HtmlGenericControl("h1");
h1.InnerHtml = "Your header content";
For more information check HtmlGenericControl Server Control Declarative Syntax
I hope this will help to you.
You can create a custom HTTP Module:
http://msdn.microsoft.com/en-us/library/ms227673.aspx
Here's an example of how to add a script to the head of each page:
How2: what event to hook in HttpModule for putting js links into head element
Related
I'm having a problem while creating dynamically a web page in ASP.NET (C#).
I need to insert multiple form tags in that page, I know that I can't put
more than one with runat="server" attribute and I don't need it.
I want to place them from C# (one for each element I've got to manage), without the runat attribute but the HtmlForm object
that I use for insert the form adds the runat attribute automatically and I can't remove it
(tried with form.Attributes.Remove("runat"))
If I use a simple string like:
"<form id="someID" method="POST" action=""></form>"
and I add it multiple times into my div it works.
The point is that I don't want to insert ALL my HTML objects writing them in a string
and add it with InnerHTML method. I'm looking for an object that manage a Form without
the runat attribute or a way to remove that from HtmlForm.
A user control is probably the cleanest solution but you can add an HtmlGenericControl instead of a HtmlForm object which isn't bound to any specific attributes.
Dim ctrl As New HtmlGenericControl("form")
ctrl.Attributes.Add("id", "someID")
ctrl.Attributes.Add("method", "POST")
ctrl.Attributes.Add("action", "")
OuterDivContainer.Controls.Add(ctrl)
If you want to add controls dynamically to a page and make the web page render them as pure html, instead of rendering asp:Controls you can use the Literal control. Check this link or this one
I've a windows .Net Form which contains a WebBrowser Control.
This WebBrowser displays a webpage based on its Url property.
Can I modify the DOM of the displayed page inside the WebBrowser control ?
If yes, how to ?
For those who are interested, here's the solution:
HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domScriptElement = (IHTMLScriptElement)scriptElement.DomElement;
domScriptElement.text = "function applyChanges(){/*DO WHATEVER YOU WANT HERE*/}";
headElement.AppendChild(scriptElement);
// Call the nextline whenever you want to execute your code
webBrowser1.Document.InvokeScript("applyChanges");
From http://msdn.microsoft.com/pt-br/library/system.windows.forms.webbrowser.aspx:
You can also manipulate the contents of a Web page through the Document property, which contains an HtmlDocument object that provides managed access to the HTML document object model (DOM) for the current page. This property is useful, when used in combination with the ObjectForScripting property, to implement two-way communication between your application code and dynamic HTML (DHTML) code in a Web page, letting you combine Web-based controls and Windows Forms controls in a single user interface. You can use the Document property to call scripting code methods from your application. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to the object that you specify for the ObjectForScripting property.
I have a page that does not have runat="server" set in the <head/> section. I do not have access to modify any of the code in the page.
This page contains a user control which I do have access to. Can I add a <meta/> tag to the head section of the page from the user control? It needs to be server-side so a javascript solution won't work.
One option is to create a Response Filter, and then modify the output before it's sent to the user.
https://web.archive.org/web/20211029043851/https://www.4guysfromrolla.com/articles/120308-1.aspx
You can parse the text in
(this.Page.Controls[0] as LiteralControl).Text
to see where the string <head> starts, and insert whatever text you need in there thus injecting your own code into the page header without it being marked with runat="server".
Please be aware though, this is pretty hacky way of getting your code where it most likely shouldn't be (otherwise the <head> element would have been marked as runat="server" so you can access it normally). This will also break if at a later date the head element is changed to be an ASP.NET control. It might will not work with master pages, you will have to walk up the control tree looking for topmost literal element.
We are supplied with HTML 'wrapper' files from the client, which we need to insert out content into, and then render the HTML.
Before we render the HTML with our content inserted, I need to add a few tags to the <head> section of the client's wrapper, such as references to our script files, css and some meta tags.
So what I'm doing is
string html = File.ReadAllText(wrapperLocation, Encoding.GetEncoding("iso-8859-1"));
and now I have the complete HTML. I then search for a pre-defined content well in that string and insert our content into that, and render it.
How can I create an instance of a HTML document and modify the <head> section as required?
edit: I don't want to reference System.Windows.Forms so WebBrowser is not an option.
I haven't tried this library myself, but this would probably fit the bill: http://htmlagilitypack.codeplex.com/
You can use https://github.com/jamietre/CsQuery to edit an html dom.
var dom = CQ.Create(html);
var dom = CQ.CreateFromUrl("http://www.jquery.com");
dom.Select("div > span")
.Eq(1)
.Text("Change the text content of the 2nd span child of each div");
Just select the head and add to it.
I use the WebBrowser control as host, and navigate/alter the document through its Document property.
Nice documentation and samples at the link above.
Are you using MasterPages?
This seems like the most obvious use of them.
The MasterPage has <asp:ContentPlaceHolder>'s for all the points where you want the content to go.
In our app we have a base controller that overrides all the View() overloads so that it reads in the name of the MasterPage from the web.config. That way customising the app is as simple as a new MasterPage and from a Controllers point of view there is no code change since our base class handles the MasterPage/web.config stuff.
I couldn't get an automated solution to this, so it came down to a hack:
public virtual void PopulateCssTag(string tags)
{
// tags is a pre-compsed string containing all the tags I need.
this.Wrapper = this.Wrapper.Replace("</head>", tags + "</head>");
}
I'm working inside of a Web User Control (.ascx) that is going to be included in a regular web form (.aspx), but I need to be able to dynamically insert code into the head of the document from the User Control. In my Coldfusion days <cfhtmlhead> would do the trick. Is there an equivalent of this in ASP.NET or a similar hack?
To add HTML markup you can do the following:
In your UserControl's code you can access Page.Header, which is itself a control. To that control you can then add new controls:
HtmlGenericControl newControl = new HtmlGenericControl("someTag");
newControl.Attributes["someAttr"] = "some value";
Page.Header.Controls.Add(newControl);
To add script markup you don't need access to the head tag at all since ASP.NET has helper methods on the ClientScriptManager that do the work for you:
Here are examples of some code you can also put in your user control's code:
// Register some inline script:
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myAlertScript", "alert('hello!')", true);
// Register a script reference:
Page.ClientScript.RegisterClientScriptInclude(GetType(), "myLibraryScript", "~/Scripts/MyScriptLibrary.js");
I realize that this is an old question, but this is another example.
Try This:
Page.Header.Controls.Add(
new LiteralControl(
"<script>alert('Literal Added to <Head>.');</script>"
)
);
If you want to add the script at a particular index of the <head> you can use
AddAt(index, new LiteralControl(...)) where index 0 equals the top of the <head>
Also, you need to add runat="server" in your head tag e.g. <head id="head1" runat="server">
this.Page.Header.Controls.Add
By doing this, you are adding controls to the head section. You can add any type of control. If you feel you need to add simple text (or you want to write the tags manually), then look into the LiteralControl class.
There's some guidance on using C# code to modify the page header here. It should work just fine from any server-side code that executes before the page load completes.
A simple e.g.
HtmlHead head = Page.Header;
HtmlTitle title = new HtmlTitle();
title.Text = "Test Page";
head.Controls.Add(title);
HTMLHead reference is in namespace
System.Web.UI.HtmlControls
Override the custom control's Load() method to add the controls or references you need into the page header while the parent .aspx page is being loaded server-side.
I have a simple solution for this. Create a runtime memory cache based on the url of the page (as a key) that holds x information about y (be it a file reference, script text, or class that generates JavaScript) and serialize its data to JSON. Newtonsoft is helpful for instances of any class. In fact, you can use it's output to initialize any new instance of a class based upon given input. In a way, that means you may have your instances of any particular class automatically instantiated despite what user control the instance is on. In the end, you create a simple web form to serve as a script reference and as the final endpoint. It pulls the JavaScript (or what've it) and spits out the client side code you need as a script reference inside the head tag.