ASP.NET dynamically insert code into head - c#

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.

Related

Adding ASP.NET User Controls at runtime via <script runat="server">

I am having trouble executing a control inside the <script runat="server"> tags in an *.aspx page.
The control works when it is defined declaratively in the HTML section of the page, but I am unable to make it work when placed within the script tag itself.
At the beginning of the page I register my control with:
<%# Register assembly="App_Web_exemple.ascx.cc671b29" namespace="Moncontrol" tagprefix="moncontrol" %>
Then, in the HTML, I call it (successfully) with the following declaration:
<moncontrol:exemple ISBN="9782894646151" runat="server" />
When I try to add it programmatically within the <script runat="server">, however, I am unable to execute it. I tried with the tags <asp:Text /> and <asp:Literal />, as follows, but that also doesn't doesn’t work.
In the HTML part:
<asp:Text id="TestControl" runat="server" />
In the script part
TestControl.Text = "<moncontrol:exemple ISBN=\"9782894646151\" runat=\"server\" />";
To clarify, what you're looking to do is programmatically add a User Control to your Web Forms page at runtime. There are a few ways of accomplishing this.
Before we begin, it's worth noting that the code you wrote likely "works" insomuch that it compiles and doesn't throw a runtime error. But it's also not executing the control. I suspect if you look at your HTML, you'll find the control declaration being output as a string literal (i.e., unprocessed by the server). It is then disregarded by the browser since it doesn't know what the <moncontrol:exemple /> tag represents. That's obviously not what you want.
Establishing a Control Container
Regardless of which approach you take, you'll want to start with some type of container on your page that you can add the control to, such as a Panel. If you don't want the container to output any wrapper markup, you can use a Placeholder:
<asp:Placeholder id="ControlContainer" runat="server" />
This serves a similar purpose as your current Text control, except its only purpose is to provide a container that you will add your user control to. From ASP.NET's perspective, however, this can be any type of server control, including a <script runat="server">, as per your request. More on that later.
Programmatically Creating the Control
Next, you're going to create the control programmatically. This is where we run into various options. The most universal approach is to use ParseControl() method (reference). This looks something like this:
Control control = Page.ParseControl("<%# Register assembly=\"App_Web_exemple.ascx.cc671b29\" namespace=\"Moncontrol\" tagprefix=\"moncontrol\" %><moncontrol:exemple ISBN=\"9782894646151\" runat=\"server\" />");
That will parse the control using the same method that processes the declarative syntax on the page, and return a Control object with your Exemple control as the first control in its Controls collection.
I find that syntax a bit sloppy, however, since it's representing a .NET object and its properties as a string literal. Given that, there are some cleaner approaches. In this case, it appears that your control is being compiled into an assembly and, therefore, likely has a Code Behind defined which inherits from UserControl. If so, you should be able to simply do something like:
Exemple control = new Exemple();
And then set the properties on it programmatically, the way you would in any other C# object. Much cleaner!
If your control was instead being compiled dynamically by the server, then you'd instead use the Reference directive with the LoadControl() method, as described in the MSDN article How to: Create Instances of ASP.NET User Controls Programmatically. I don't believe that method will work for you, however.
Adding the Control Instance to the Page
Regardless of which approach you take, the next step is the same: you then add the control you've programmatically added to your page by adding it to the Controls collection of the target container. E.g.,:
ControlContainer.Controls.Add(control);
Note: You can technically just add this to the Page class's Control collection, too, but that doesn't give you any control over where on the page it is placed; having a PlaceHolder control (or equivalent) lets you specify exactly where you want the control to appear.
I hope this helps. There are a couple of caveats depending on how you wrote and compiled your control, but this should give you the basic structure needed to address your problem.

ASP.NET Website: page with multiple forms

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

Create Handler that manipulates head tag

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

Can I modify the <head/> section of a Page in .NET from a User Control without runat="server"?

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.

Methods for dynamically building JavaScript within an ASPX page?

I have a page that is referenced via a <script> tag from a page on another site. In the script src, I pass in the form I want my script to build (from a db table), and the div where the dynamically built form should go. The calling page looks something like this:
<div id="FormContainer"></div>
<script type="text/JavaScript" src="http://www.example.com/GenerateForm.aspx?FormId=1&div=FormContainer"></script>
GenerateForm.aspx contains the code that reads the QueryString parameters for the FormId, and the Div Id, and outputs JavaScript that will build the form.
My question is this. What are the different methods for "outputting" the JavaScript? Some of the JavaScript is static, and can be packaged into an external .js file and I have jQuery too. But should I add that on the GenerateForm.aspx markup page? Or should I use a ScriptManager?
And what about the dynamically built JavaScript? Currently I'm just using Response.Write() for a proof of concept, but instead, should I be doing something else? Use a Literal control on the page and set its value? Use a ScriptManager? Something else?
I know this is a verbose question, so thanks in advance!
If you want to use a seperate, referenced Javascript file, you probably want to do is use an ashx file. Basically this is just a generic handler that you'll use to write directly to the output stream without having to deal with the ASP.NET page lifecycle. If you add a basic Generic Handler (.ashx) to your site from the Add New Item dialog, the template should be enough direction, using context.Response.Write() to output your Javascript dynamically.
The ScriptManager is more useful if you want to output individual lines of Javascript to be ran at certain times, like after an event has fired. Then you can do ScriptManager.RegisterClientBlock(this, this.GetType(), "CodeBlock", "alert('Button clicked');", true); to show a client alert box after a button has been clicked, for example.
Static files should be handled just that way - statically. The server can handle the caching, and does not cause unnecessary processing if you reference the static script file directly from the script tag. However, if you need to load a static script dynamically, you could, for example, create a literal that had the <script> tag inside it. This way it uses the browser's cached version of the static file.

Categories

Resources