How to generate css by database in asp.net..? - c#

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"});
});

Related

Get full source of a webBrowser

I have a webBrowser:
webBrowser1.DocumentText = #"<html lang='en'>
<head>
<meta charset='utf-8'>
<title></title>
<style type='text/css'>
.red
{
color: red;
}
</style>
</head>
<body>
<div class='red'>red text</div>
sad adad a das
</body></html>";
I want to get the full source of the webBrowser:
textBox1.Text = webBrowser1.DocumentText;
But it results only:
<HTML></HTML>
It works if I display in a MessageBox before set the textBox1.text:
MessageBox.Show(webBrowser1.DocumentText);
It's weird. How can I get the full source?
Here is a proper way to display HTML from string in WebBrowser control
var html = #"<html lang='en'>
<head>
<meta charset='utf-8'>
<title></title>
<style type='text/css'>
.red
{
color: red;
}
</style>
</head>
<body>
<div class='red'>red text</div>
sad adad a das
</body></html>";
webBrowser1.DocumentText = "0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(html);
webBrowser1.Refresh();
// Will return html you provided
textBox1.Text = webBrowser1.DocumentText;
To answer your initial question directly, how to get FULL SOURCE no matter what:
WebBrowser1.Document.GetElementsByTagName("HTML").Item[0].OuterHtml;
Make it a habit to use this and NOT DocumentText because if you make any changes to DocumentText after it's been set, for example, changing the InnerHTML of a tag, those changes wont save to DocumentText.
I just slapped a TextBox onto one of my WinForms and updated the text to the above code and it shows all my HTML without issue. Here's an example of me filling in my WebBrowser in case you've got a typo or something in your code:
WebBrowser1.Navigate("about:blank");
WebBrowser1.Document.OpenNew(false);
WebBrowser1.Document.Write("<html><head><title></title></head><body></body></html>");
I never had any luck writing the DocumentText directly. This method worked without issue.

Dynamic styles aren't being applied

I have a menu that I've built styles for and have some menu options that should not be shown to non-admin users. I've put a link to an asp.net page as a dynamic style. Here is the code:
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/DynamicStyle.aspx" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
the source of DynamicStyle.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if(!Roles.IsUserInRole("Administrators"))
{
StringBuilder oSb = new StringBuilder();
oSb.AppendLine(".restricted");
oSb.AppendLine("{");
oSb.AppendLine("display: none;");
oSb.AppendLine("}");
Response.Write(oSb.ToString());
Response.End();
}
}
I have verified that it does emit the proper CSS.
here is a snip of the code that should be hiding the button:
<li>Events</li>
<li>Industries</li>
<li class="restricted">Institutions</li>
<li>Job Groups</li>
<li>Job Titles</li>
In Mozilla's inspector, it does not list the restricted as having been applied.
I have never tried to do this this way but have seen it done and am wondering what I am missing? Any help is appreciated.
You aren't returning the correct content type for CSS (it's returning type of text/html instead of text/css). Your code would work if you add Response.ContentType = "text/css";:
Response.ContentType = "text/css";
Response.Write(oSb.ToString());
Response.End();
But the real problem is you are simply "hiding" links that people shouldn't see... but if they view the page source, they can still see them. A better option is to not send those links to the client at all. One option is:
<li id="_admin1" runat="server">Institutions</li>
and then in your code behind:
_admin1.Visible = Roles.IsUserInRole("Administrators");
Now the html for that <li> won't even be sent to the client unless they are in the correct role.

Adding CSS at runtime to an ASP.net master page.

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.

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