Adding CSS at runtime to an ASP.net master page. - c#

I have an ASP.net web application, and would like to know if is it possible to change the CSS of a site at run time of a master page, and get the CSS file name from a SQL database and add it into the system ?

You can put on the top of the masterpage on aspnet literal and construct the link in the pageload of the masterpage that way you could put a css there
<asp:Literal ID="Css" runat="Server" />
Then on the page load
var cssfilename = GetCssFromDatabase();
Literal.Text = "<link rel=\"stylesheet\" media=\"all\" " + cssfilename + "\" />";

Yes it is. Use <head runat="server"> and you can put anything in there, simplest way probably a Literal control where you append the string from codebehind
Masterpage.master:
<head runat="server">
<title>Your Site</title>
<asp:Literal runat="server" ID="cssLiteral" />
</head>
Masterpage.master.cs:
cssLiteral.Text = "<link rel='stylesheet' type='text/css' href='"+strCssFileName+"' />";

You haven't provided much information of your case, yes it's possible in many ways. Here is a simple example how to change css-file in master-page from a content page:
First add a static variable for example in Global.asax (code in VB.Net)
Public Shared DefaultCssFile As String = "~/MyStyles.css"
In master pages header:
<asp:PlaceHolder runat="server">
<link rel="Stylesheet" type="text/css" href="<%= Page.ResolveUrl(MyApp.Global_asax.DefaultCssFile) %>" />
</asp:PlaceHolder>
Then just change the variables value as you see fit.
MyApp.Global_asax.DefaultCssFile = "~/MyOtherStyles.css"

There are several ways you can achieve this.
Best way I suggest you to use theme and skin file concept.
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "BlueTheme";
break;
case "Pink":
Page.Theme = "PinkTheme";
break;
}
}
here you can change the values of your theme run-time from code behind accurately. you can put your .css files into different themes. and as per database conditions you can change values of theme files.
hope this will help.

Related

ASP Master and Content Page

I am using Master and Content Pages, now I have a situation that I dont want to use the css of Master page on Content Page.
There are alots of classes and css files so overriding them is not possible I just have option to not include them in content page.
So what are the possible scenarios?
Having in mind that every equivalent method between the MasterPage and the ContentPage is being executed always later by the MasterPage (see here), we have to introduce the CSS change inside the MasterPage.
That being said, you can detect the name of the ContentPage actually being displayed inside the Masterpage using Page.AppRelativeVirtualPath.ToString() in your ContentPlaceHolder.
Then, you can modify the css inside the masterpage saving it in an asp:Literal that includes the HTML link tag.
For example:
MasterPage.aspx
<head>
<asp:Literal runat="server" ID="cssStyleSheet">
</head>
<body>
<asp:ContentPlaceHolder ID="contentPageHolder" runat="server">
</body>
MasterPage.aspx.cs
public void ModifyCSS(){
string contentPageName = contentPageHolder.Page.AppRelativeVirtualPath.ToString();
int pos = contentPageName.LastIndexOf("/") + 1;
contentPageName = contentPageName.SubString(pos, contentPageName.Length -pos);
switch(contentPageName)
{
case "Login.aspx":
cssStyleSheet.Text = #"<link rel='stylesheet' type='text/css' href='Styles/Login.css' />";
break;
case "Logout.aspx":
cssStyleSheet.Text = #"<link rel='stylesheet' type='text/css' href='Styles/Logout.css' />";
break;
}}

How to generate css by database in asp.net..?

I want to change the content of style sheet dynamically like:
.menu
{
color: #333333;
Font-size : 12px;
}
I want to change the color and font size dynamically.
How to replace value of color (like #333333 to #ffffff) and font size (12px to 14px) dynamically.
I am finding the way to use variables in stylesheet, and assigning it to attributes that can make my work easy.
Waiting for reply with example.
If you use asp.net, use inline html. Read here
<div style="font-size: <% Response.Write(i)%>">
Hello World<br />
</div>
I am not pretty much sure that you can use variables in stylesheets, what I think a way around for it is to generate the style sheet at run time and assign it to the page.
In you asp.net page you can have like:
<head>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<asp:literal id="literalCss" runat="server"></asp:literal>
</head>
and than in your code behind you can use:
private void Page_Load(object sender, System.EventArgs e)
{
// create css file here for the specific user and save it in a folder,
// give a meaning full name to file, if user specific you can append user id in name like
string fileName = "cssFile_" + userid + ".css";
literalCss.Text = #"<link href='/style/" + fileName + "' rel='stylesheet' type='text/css' />";
}
I hope it can help you out.
You may use JavaSctipt with JQuery:
$("#myButton").Click(function()
{
$(".menu").css({"color":"#ffffff","font-size":"14px"});
});

Handle every user input as plain text

We have a really big web-application.
About 120.000 lines in total.
In this application the user has plenty possibilities to enter text.
In the user information, folders, groups and so on.
Some of the users want to name different objects like Age < 20.
There was a problem because ASP.NET blocks such input because of the "<" to prevent javascript-injections.
We found a way to shut those safety-mechanisms down but now our application is unsafe.
So the question is:
Is there any setting or property or whatever that can be set global (at one point for the whole application) that the application handles such input as plain text?
So when a user for example wants to name a folder <script>alert("ALERT");</script> it should be named that way and is shown just as <script>alert("ALERT");</script> but the script will not execute.
The same for HTML: if its named Folder<br>One it should look like: Folder<br>One and not like:
Folder
One
Of course i could use HTML-Encode/-Decode but i dont want to go through the whole project and add an Encoding/Decoding wherever an input is made or shown...
Also would a global solution pretent mistakes in the future development.
So again the Question: is there any way to handle every text just as text? And all that as global as possible?
Hope you could understand my problem and know any possibilities.
If you are using JQuery, whenever you set your value to any span or div,
Use:
$('#myDiv').text('<script>alert("a")</script>');
And Don't use:
$('#myDiv').html('<script>alert("a")</script>');
or
$('#myDiv').innerHTML='<script>alert("a")</script>';
if you dont want to use HTML encode decode than try ValidateRequest="false" You can do it like in code bellow:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" ValidateRequest="false" Inherits="_Default" %>
Another technique you may want to use is as following..
<script>
function Encode() {
var value = (document.getElementById('TextBox1').value);
value = value.replace('<', "<");
value = value.replace('>', ">");
document.getElementById('TextBox1').value = value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Encode()" />
</form>
Server-Side
protected void Page_Load(object sender, EventArgs e)
{
this.TextBox1.Text = Server.HtmlDecode(this.TextBox1.Text);
}

How do I implement a CSS class in a control on my web form in ASP .NET?

I have a file in my project called StyleSheet.css.
Here, I have the classes for each element on my web form.
For example:
.selectEnvironment
{
background-color: #FF0000;
}
Then I go to my control on my web form (a drop down list) and I add the CSS class to it:
<div>
<asp:DropDownList ID="ddlEnvironment" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlEnvironment_SelectedIndexChanged" CssClass="selectEnvironment">
<asp:ListItem>Select Environment</asp:ListItem>
<asp:ListItem>Development</asp:ListItem>
<asp:ListItem>Staging</asp:ListItem>
<asp:ListItem>Production</asp:ListItem>
</asp:DropDownList>
</div>
This is not working. The background color of this is not changing to red.
What am I doing wrong? I'm completely new to front end web development.
You must register your style
<head runat="server">
<style type="text/css">
...
</style>
</head>
You can also use this line
<link href="MyStyles.css" rel="stylesheet" type="text/css" />
You can also register in your code Behind
protected override void OnInit( EventArgs e )
{
this.Header.InnerHtml += "<link type=\"text/css\" rel=\"Stylesheet\" href=\"styleSheet.css\" />";
base.OnInit(e);
}
Add your style to the head portion of the MASTER PAGE. Or link the CSS.
Then add the CSSCLASS to the dropdown menu.
Run and see the magic. It will work.
Check below.
LET ME KNOW IF THAT HELPS.
Regards,
Pradie
Drag style sheet from Solution Explorer into your page, or master page header, in design view. This is the easiest way to make sure that the style sheet path is correct ;-)

Adding meta tag programmatically in C#

I'm trying to programmatically add a <meta>. It is working fine when there is a Head element with runat = "server" in the .aspx page.
The code behind is:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Header.Controls.Add(meta);
But I have some script in the head tag which contains code blocks like <% ... %>, so I cannot keep the runat = "server" value.
The problem is I have to add the meta tag programmatically, because it depends on a value from the database.
Is there a way to solve this issue so that my script inside the head element works as usual and I can add a meta tag programmatically?
OK, I tested the answer by veggerby, and it works perfectly:
In the <header> section:
<asp:PlaceHolder id="MetaPlaceHolder" runat="server" />
Note that Visual Studio might show a warning on the PlaceHolder tag, because it is not recognised as a known element inside the header, but you can ignore this. It works.
In the C# code:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
MetaPlaceHolder.Controls.Add(meta);
Alternatively (since you already have code blocks using <% %> in your header section), you can tag the meta directly and retrieve only the value from server side:
<meta name="robots" content="<%=GetMetaRobotsValueFromDatabase()%>" />
Many thanks to Awe for the solution! I have implemented this code in a (error404.ascx) ASP.NET User Control as follows:
<%# Control Language="C#"%>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.TrySkipIisCustomErrors = true; //Suppress IIS7 custom errors
Response.StatusCode = 404;
SetRobotsHeaderMetadata();
}
private void SetRobotsHeaderMetadata()
{
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Master.FindControl("cphPageMetaData").Controls.Add(meta);
}
</script>
With the following masterpage:
<%# Master Language="C#" AutoEventWireup="true" Inherits="MyMaster" %>
<script runat="server">
...
</script>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>Site title here</title>
<asp:contentplaceholder runat="server" id="cphPageMetaData">
</asp:contentplaceholder>
</head>
<body>
...
</body>
</html>
Or you could just put your meta-tag in the header, with an ID and a runat="server"... then in the code behind say
myMetaTag.Content = "noindex,follow";
or
myMetaTag.Visible = false;
or whatever you'd like.
I think this is the best approach:
this.Page.Header.Controls.Add(new LiteralControl(#"<meta ... />"));
Enjoy!
Try moving whatever it is that you are doing in the <% .... %> to the code-behind. If you are using the script to add content into the page, you can replace it with an asp:Literal control and then set the value you were previously calculating in the script block to the code-behind and set Literal.Text to that value.
I haven't tested it, but maybe you can add an <asp:Placeholder> inside the <head></head> tag and add the meta tags to this.
The best solution for this, which I successfully checked without any error or warning:
The JavaScript code, which contains the <% ... %> code, was removed from the head section and placed in the body section.
You could define your meta tag as a static string like so:
Private Shared MetaLanguage As String =
String.Format("<meta http-equiv=""Content-Language"" content=""{0}""/>", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName)
Then place them in your head like so:
<head runat="server">
<%=MetaLanguage%>
</head>
This allow you to use any meta tag values and is easy to read and customize. Note: The use of the Shared keyword (static) helps improve performance.
MetaDescription = "Your meta description goes here";
MetaKeywords = "Keyword1,Keyword2,Keyword3";
OK... I actually only use C#... Or HTML into C#. I never use codebehind, designer or webcontrols in the file aspx... So I program everything from classes... And dynamically.
Result:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
`meta.Content = "Here is what you want";`
var page=HttpContext.Current.Handler as Page;
page.Header.Controls.Add(meta);

Categories

Resources