How to add Script in the Page <head></head> dynamically - c#

I use asp.net 4 and c#.
I have a Web User Control inside a Web From page.
When I include the Web User Control I would like also include programmatically some script within the tags for the final generated page.
Any idea how to do it?
Maybe ScriptManager could help on this?
Please provide me a sample of code I'm pretty new at developing thanks for your time on this!

Peter's answer will add to the page, but not the head element. Take a look at this article:
http://weblogs.asp.net/johnkatsiotis/archive/2008/08/08/add-scripts-to-head-dynamically.aspx
It provides a nice clean way to add a script to the head element using an extension method.

I realize that this is an old question, but there is a much simpler way.
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, joelmdev mentioned in a comment you need to add runat="server" in your head tag e.g. <head id="head1" runat="server">

Take a look at RegisterClientScriptBlock of the ClientScriptManager.
From MSDN:
...
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
...

Related

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

Displaying html links in a different order on page load

I have a bunch of static links currently within a div, however Im after changing the order of the links on page load.
I've considered using a literal and a loop through the links in code behind but im stumped. Maybe a repeater... I need a push in the right direction please!
Im fairly new to this so any help would be much appreciated. Thanks
(c# or vb.Net)
ok so lets say that you would store the links in a Links.txt file because there could be hundreds of links for example..
1. Create the .txt file
2. Make note of the file location.
3. Save the file with the links in them
4. use this code in your project to load the links
List<string> strUrlLinks = new List<string>(File.ReadAllLines(FilePath + FileName.txt));
in code you can then hover over strUrlLinks and you will see the Links
to access the individual links do it based on it's [Index] position
I know you asked for an answer in c# or vb.net and may have some technical restraints on this, but to create this functionality in jQuery is almost trivial considering the links are already hardcoded on the page.
See the example below which sorts in descending order on the link text.
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="linksContainer">
Line 1
Line 3
Line 2
</div>
<script type='text/javascript'>
$(window).load(function(){
var orderDivLinks = function(desc) {
$('div#linksContainer').children().detach().sort(function(a,b) {
var compA = $(a).text();
var compB = $(b).text();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
}).appendTo(document.body);
}
orderDivLinks(0);
});
</script>
</body>
</html>

Load javascript code after loading code behind

I have a web site released at facebook platform, i am using C# .Net 2008, the problem is that i am loading an array elements from code behind in javascript arary and i am loading elelment element using the following javascript code :
ArList = new Array('<%=ListOfWords[0]%>','<%=ListOfWords[1]%>','<%=ListOfWords[2]%>','<%=ListOfWords[2]%>');
the problem that when i call an element from the array as follows :
document.getElementById("WordDiv").innerHTML = ArList [0];
The element is not set with the value inspite the array in the code behind has values and i don't know why the value of the array element is not set ? and in some cases i found it loaded with value and everything go right so may be it's a problem in rendering so the value of code behind is not seen in client side ? or where is the problem come ?
and when i traced the application in IE i found the status bar report a javascript error then disappered and say done and when the yellow allert appears in the status bar i have clicked it and noticed the message says : object expected.
The problem now is that in onload event of the body tag i call a function in the javascript that intialize the javascript array with values from code behind array and the problem is that in some cases the function is not entered as i traced it by putting an alert in the begining of the function and i found that when the javascript array is not filled the code of the function is not entered as the alert is not showed so i don't know how to force the DOM to enter this function which i call it in the tag here sample of the code:
javascript code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body onload="IntializeArr(); return false;">
<form id="form1" runat="server" >
..........Some Controls...............
</form>
<script type="text/javascript" language="javascript">
var TList;
var BList;
function IntializeArr()
{
TList = new Array('<%=ListofT[0]%>','<%=ListofT[1]%>','<%=ListofT[2]%>','<%=ListofT[3]%>','<%=ListofT[4]%>','<%=ListofT[5]%>','<%=ListofT[6]%>','<%=ListofT[7]%>','<%=ListofT[8]%>','<%=ListofT[9]%>');
BList = new Array('<%=ListOfB[0]%>','<%=ListOfB[1]%>','<%=ListOfB[2]%>','<%=ListOfB[3]%>','<%=ListOfB[4]%>','<%=ListOfB[5]%>','<%=ListOfB[6]%>','<%=ListOfB[7]%>','<%=ListOfB[8]%>','<%=ListOfB[9]%>');
}
</script>
</body>
</html>
C# Code :
public string[] ListOfB = new string[15];
public string[] ListofT = new string[15];
And the code behind array is filled from data returned from database and they are filled i have traced them and each time and they are filled and i found that the problem from javascript i don't know if it is from facebook platform or from my code but i think that it is not from my code as the problem that i call a function in the onload of the tag and the function is not entered and this is the problem so can any one help me please
Hope that i will find a solution as i got depressed
If the IntializeArr() function is not being called, it is most likely a javascript error in the page, and most likely caused by some invalid javascript characters in the ListofT or ListofB arrays.
You should be escaping any single quotes or newlines.
Easiest way to check is to just "view source" in the browser once the page has loaded. Look down to your script and find what values were put it and you should see if there were any errors.
Maybe ListofWords[0] contains an apostrophe?
Are you outputting the JS array creation to the page inside <script> tags?
You have to emit that javascript so that the browser can run it - then ArList will be available on the page to other javascript.
Agree, more code example is needed.
Usually I solve something like this by using Sys.Application.add_init() or $(document).ready(). However there are other possible solutions. Use an AJAX request to get the array. Or something like:
function setInnerHtml() {
if (typeof(ArList) != "undefined") {
document.getElementById("WordDiv").innerHTML = ArList[0];
} else {
setTimeout("setInnerHtml()", 40);
}
}

ASP.NET dynamically insert code into 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.

Force browser to use new CSS

Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?
I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string:
<link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" />
I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on...
Without using js, you can just keep the css filename in a session variable. When a request is made to the Main Page, you simply compose the css link tag with the session variable name.
Being the ccs file name different, you force the broswer to download it without needing to check what was previusly loaded in the browser.
As jeroen suggested you can have somthing like:
<link href="StyleSelector.aspx?foo=bar&baz=foz" type="text/css" rel="stylesheet" />
Then your StyleSelector.aspx file should be something like this:
<%# Page Language="cs" AutoEventWireup="false" Inherits="Demo.StyleSelector" Codebehind="StyleSelector.aspx.cs" %>
And your StyleSelector.aspx.cs like this:
using System.IO;
namespace Demo
{
public partial class StyleSelector : System.Web.UI.Page
{
public StyleSelector()
{
Me.Load += New EventHandler(doLoad);
}
protected void doLoad(object sender, System.EventArgs e)
{
// Make sure you add this line
Response.ContentType = "text/css";
string cssFileName = Request.QueryString("foo");
// I'm assuming you have your CSS in a css/ folder
Response.WriteFile("css/" + cssFileName + ".css");
}
}
}
This would send the user the contents of a CSS file (actually any file, see security note) based on query string arguments. Now the tricky part is doing the Conditional GET, which is the fancy name for checking if the user has the page in the cache or not.
First of all I highly recommend you reading HTTP Conditional GET for RSS hackers, a great article that explains the basics of HTTP Conditional GET mechanism. It is a must read, believe me.
I've posted a similar answer (but with PHP code, sorry) to the SO question can i use “http header” to check if a dynamic page has been changed. It should be easy to port the code from PHP to C# (I'll do it if later I have the time.)
Security note: it is highly insecure doing something like ("css/" + cssFileName + ".css"), as you may send a relative path string and thus you may send the user the content of a different file. You are to come up with a better way to find out what CSS file to send.
Design note: instead of an .aspx page you might want to use an IHttpModule or IHttpHandler, but this way works just fine.
Answer for question 1
You could write a Server Control inheriting from System.Web.UI.Control overriding the Render method:
public class CSSLink : System.Web.UI.Control
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if ( ... querystring params == ... )
writer.WriteLine("<link href=\"/styles/css1.css\" type=\"text/css\" rel=\"stylesheet\" />")
else
writer.WriteLine("<link href=\"/styles/css2.css\" type=\"text/css\" rel=\"stylesheet\" />")
}
}
and insert an instance of this class in your MasterPage:
<%# Register TagPrefix="mycontrols" Namespace="MyNamespace" Assembly="MyAssembly" %>
...
<head runat="server">
...
<mycontrols:CSSLink id="masterCSSLink" runat="server" />
</head>
...
You should possibly just share a common ancestor class, then you can flick it with a single js command if need be.
<body class="style2">
<body class="style1">
etc.
I like jeroen's suggestion to add a querystring to the stylesheet URL. You could add the time stamp when the stylesheet file was last modified. It seems to me like a good candidate for a helper function or custom control that would generate the LINK tag for you.
I know the question was specifically about C# and I assume from that Windows Server of some flavour. Since I don't know either of those technologies well, I'll give an answer that'll work in PHP and Apache, and you may get something from it.
As suggested earlier, just set an ID or a class on the body of the page dependent on the specific query eg (in PHP)
<?php
if($_GET['admin_page']) {
$body_id = 'admin';
} else {
$body_id = 'normal';
}
?>
...
<body id="<?php echo $body_id; ?>">
...
</body>
And your CSS can target this:
body#admin h1 {
color: red;
}
body#normal h1 {
color: blue;
}
etc
As for the forcing of CSS download, you could do this in Apache with the mod_expires or mod_headers modules - for mod_headers, this in .htaccess would stop css files being cached:
<FilesMatch "\.(css)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>
But since you're probably not using apache, that won't help you much :(
Like in correct answer, i am using some similar method, but with some differences
<link href="mystyle.css?v=DIGIT" type="text/css" rel="stylesheet" />
As a DIGIT you can use a real number, set manually or automatically in your template. For example, on my projects i'm using Cache clearing modules in admin panel, and each time use this cache cleaner, it increments the DIGIT automatically.

Categories

Resources