Implementing style sheet code dynamically
 
Published: 06 Feb 2008
Abstract
This article examines the different ways in which you can implement style sheets dynamically. Initially, you will learn the dynamic implementation using JavaScript code. Frans then explores the process of working with style sheet code from the database. He wraps up the article by providing some tips to further enhance the style sheet code. The article is supported by relevant source code and a sample application is provided at the end.
by frans eilering
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 33379/ 59

Introduction

Many clients want to have their own style implemented on the page after they have logged in. I inserted some style sheet code in the database just by copying and pasting the content of a normal style sheet. Then I retrieved this record from the database, put it in a variable, and inserted it in my page dynamically.

Implementing JavaScript code dynamically

To implement JavaScript code dynamically there are two functions available.

Listing 1

Page.ClientScript.RegisterStartupScript(GetType(Page), "item1", script)

and

Listing 2

ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "item1", script, True)

The last may be used if you have an AJAX enabled website and a ScriptManager on it.

Listing 3

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

The difference between both is that the first one will put the script code at the end of the page and the second one will put the script code just behind the <BODY> tag.

A second difference is that the first one needs a <script> tag to be added and in the second one these tags will be put there for you.

Suppose my code looks like

Listing 4

Protected Sub Page_Load(ByVal sender As ObjectByValAs System.EventArgs) _
  Handles Me.Load
        Dim script As String
        If Not Page.IsPostBack Then
            script = "<script type='text/javascript'><!--" & vbCrLf & _
               "alert('Alert message two');" & vbCrLf & "// --></script>"
            Page.ClientScript.RegisterStartupScript(GetType(Page), "focus4", _
               script)
            script = "alert('Alert message one');"
            ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), _
               "item11", script, True)
        End If 
End sub

Then I will have two alert boxes; the first one "alert message one" although it is called secondly and a second one "Alert message two".

You might even have your alert message hard coded in the <BODY> of your page.

Listing 5

<script type="text/javascript">
<!--
alert('in between');
 -->
</script>

This message will come after the first one and before the last one. Also the alert message implemented with the following code will pop up when the page is loaded.

Listing 6

Page.ClientScript.RegisterStartupScript 

The alert message implemented with Listing 7 will pop up before the page is loaded.

Listing 7

ScriptManager.RegisterClientScriptBlock

A third method for implementing your code dynamically is this.

Listing 8

<head>
<title><% =titelpage%></title>
<% =MyNewStyle%>
</head>

In the code for the page you must fill the variable MyNewStyle.

Listing 9

Protected MyNewStyle As String 
Protected titelpagina As String 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
  Handles Me.Load
   titelpagina = "new title"
   MyNewStyle = "<style type='text/css'>TD{color:orange;border:1;" & _
       "border-color:black;border-style:solid;}</style>"
End Sub
And it is easy to fill this dynamically
Implementing a style

As you know you may implement a style or a style sheet in the <HEAD> tag of your page.

Listing 10

<head>
<style type="text/css">TD{color:Navy;
border:10;
border-color:green;
border-style:solid;}</style>
</head>

What would happen if I change the JavaScript code in the previous example to style sheet code?

Listing 11

script = "<style type=""text/css"">TD{color:Navy;border:10;" & _
  "border-color:red;border-style:solid;}</style>"
Page.ClientScript.RegisterStartupScript(GetType(Page), "focus5", script)

Because the ScriptManager automatically adds the <javascript>  tags to your code, you must first undo this <javascript> code with an end tag, then insert your style and then start the <javascript> tag again.

Listing 12

script = "<style type=""text/css"">TD{color:Navy;border:20;" & _
  "border-color:blue;border-style:solid;}</style>"
script2 = "--></script>" & script & "<script type=""text/javascript""><!--"
ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "tekst", _
  script2, True)

In case you have both the

Listing 13

ScriptManager.RegisterClientScriptBlock

and the

Listing 14

Page.ClientScript.RegisterStartupScript 

then the last one will override the first one because the last one is the last on the page.

Using this you may put whatever you want. You even may change the title of your page and you also may implement a style sheet. I case you want to implement the <head> tag from code, it must be removed from youre static HTML code.

Listing 15

Dim script4 as String
Dim MyNewTitle as Sring = "item4"
Dim MyStyleSheet as String = "Croon.css"
 
script4 = vbCrLf & vbCrLf & "style sheet and title to " & _
MyNewTitle & "<BR/><head runat=""server""><title>" & _
MyNewTitle & "</title><link href=" & _
MyStyleSheet & " rel=""stylesheet"" type=""text/css"" /></head>"
 
Page.ClientScript.RegisterStartupScript(GetType(Page), "item8", script4)

Style sheet code from the database

I assume you know how to retrieve data from your database.

Suppose my normal css style sheet contains

Listing 16

BODY{background-color:Orange;color:Aqua;} 
TABLE{border:1;border-style:solid;}  
TD{color:Navy;}

I change it to

Listing 17

<style type='text/css'>
BODY{background-color:Orange;color:Aqua;} 
TABLE{border:1;border-style:solid;}  
TD{color:Navy;}
</style>

Now select this text, copy it and paste it in a record field of your database.

Then in code fill the script variable

Listing 18

Protected Sub Page_Load(ByVal sender As ObjectByValAs System.EventArgs) _
 Handles Me.Load
  Dim script As String
  If Not Page.IsPostBack Then
   script = READ THE DATA FROM THE DATABASE
   Page.ClientScript.RegisterStartupScript(GetType(Page), "focus5", script)
   script2 = "--></script>" & script & "<script type=""text/javascript""><!--"
   ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "tekst", script2,
   True)
 End If 
End sub

Changing style in another way

If you want to switch to another style you may implement some JavaScript code like styleswitch.js. This works but if you have many clients who want to have their own style sheet, it may become unclear.

A second way of changing the look of your page dynamically may be through JavaScript code like

document.body.style.backgroundColor='red';"

But how do you distinguish between your clients? Each client might have its own color. You also must know the proper code for each control in JavaScript and you must know how to implement it dynamically.

Main page

Listing 19

BODY
      {
      border: 0;
      border-style:solid;
      font-size:small;
      font-family:verdana;
      background-color:yellow;
      }

And attached it to my TML code

Listing 20

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="HEAD1"><title>Telefoon applicatie </title>
    <link href="Croon.css" rel="stylesheet" type="text/css" />
    </head>

I created a main.aspx page, an ASP.NET Ajax enabled website and inserted a ScriptManager into my page.

Secondly, I inserted a reference to my normal style sheet.

The complete HTML code looks like

Listing 21

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" 
Inherits="_Default"%>
<span style='background:yellow'> </span>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
        <link href="Croon.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>This text would be in Verdana from the normal style sheet. 
I changed it dynamically in Courier.
            &nbsp;</div>
    </form>
</body>
</html>

In the code behind I put

Listing 22

Partial Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
      Handles Me.Load
        Dim script1 As String
' Session("StijlScript") may be filled the way you want. 
' For this article I filled it with text.
        HttpContext.Current.Session("StijlScript"= "<style type='text/css'>" & _
            "BODY {" & _
            vbCrLf & "    background-color: red;" & _
            vbCrLf & "    font-family:courier;" & _
            vbCrLf & "    font-weight:normal;" & _
            vbCrLf & "    color:red;}" & _
            vbCrLf & "</style>"

'I inserted a vbCrLf just for the look. You also may have it in one string

HttpContext.Current.Session("StijlScript") = "<style type='text/css'>" & _
    "BODY{background-color: red;font-family:courier;" & _
    "font-weight:normal;color:red;}</style>"
 
'Then put the pieces together
        script1 = vbCrLf & "--></script>" 'to end the javascript code
 
        script1 = script1 & vbCrLf & HttpContext.Current.Session("StijlScript")           
        script1 = script1 & vbCrLf & "<script type=""text/javascript""><!--"
'and execute it        
  ScriptManager.RegisterClientScriptBlock(CType( _
  Page.FindControl("scriptManager1"), Object), _
  CType(Page.FindControl("scriptManager1"), Object).GetType, _
  "RefreshMap", script1, True)
' RefreshMap is a unique name if you want to refer to this script later.
 
    End Sub
End Class
Result

The page would have a yellow background without the ScriptManager.RegisterClientScriptBlock. I changed it dynamically to red.

Each item in MyCode will override the style in my CSS sheet. If I don't use an item, the style in the CSS sheet will be used.

Downloads

References

Conclusion

In this article, you have learned how to implement style sheet code dynamically with the help of source codes.



User Comments

Title: script   
Name: john
Date: 2012-12-23 1:59:57 AM
Comment:
great article

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 11:34:46 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search