Thursday, 2 August 2012

How to Add Scripts to Header Dynamically in ASP.Net


Dynamically adding controls to header is really pretty straightforward. In order to add JavaScript to a master page’s head section. We can just go ahead and dynamically build some HtmlGenericControls to contain our JavaScript, then inject them.

So here’s the markup for your master page’s head section:

<!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">
<title></title>
</head>

Note:- head is set to runat the server. That’s because, if it is not running at the server, we can’t access the master page’s Page.Header property, which we need to be able to access in order to directly add our script tags to the page.

Now,You then just add the following code to the page’s Page_Load event handler:

string strJScript = string.Empty;
strJScript = @"<script type='text/javascript'>
......// Add your script code //.......................
</script>";
LiteralControl jsScript = new LiteralControl(strJScript);
Page.Header.Controls.Add(jsScript);


That's it! Javascript, CSS files, Meta Tags and anything else can be inserted to the header dynamically!!

1 comment: