I need to add to the page from within a custom control. I can't use a stylesheet (.css) because I'm using a url(...) and need to resolve the url.
Right now I'm doing:
Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));
But I'm hoping for something a touch more elegant?
I guess it's not a bad solution for the problem. If you had an external stylesheet file, this piece of code will do the work:
HtmlLink cssRef = new HtmlLink();
cssRef.Href = "styles/main.css";
cssRef.Attributes["rel"] = "stylesheet";
cssRef.Attributes["type"] = "text/css";
Page.Header.Controls.Add(cssRef);
Another idea is to write your own ASP.NET ServerControl "HtmlInlineStyle", so you could call it this way (script tags would be done by your server control):
Page.Header.Controls.Add(
New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");
This blog entry and the comments show some alternatives (ScriptManager.RegisterClientScriptBlock). But in my opinion your solution is okay.
Here's another way... For example:
Parent ASPX portion:
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
Within the Control:
Dim xyzStyle As New Style()
xyzStyle.CssClass = "xyz"
xyzStyle.BackColor = Drawing.Color.LightBlue
Page.Header.StyleSheet.CreateStyleRule(xyzStyle, Nothing, ".xyz")
Note that this assumes that the parent ASPX page has the class attribute set for the target control. If not, then you will need to merge the style with the control using the MergeStyle method. (This requires that the control be runat="server").
This code renders the following output: (Showing entire source for your convenience)
<html>
<head>
<title>Untitled Page </title>
<style type="text/css">
.xyz { background-color:LightBlue; }
</style>
</head>
<body>
<form name="form1" method="post" action="MyPage.aspx" id="form1">
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
</form>
</body>
</html>
I create my own class and inherit Style, with my own dictionary for attributes that the default Style class does not include. Here is a brief example...
protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver)
{
Dictionary<String, String> _styles = new Dictionary<string, string>();
_styles.Add("display", "inline-block");
foreach (String s in _styles.Keys)
{
attributes[s] = (String)_styles[s];
}
base.FillStyleAttributes(attributes, urlResolver);
}
Related
i want to render css in page conditionally based on cookie. at my server side i detect cookie and store the cookie value in variable and now in aspx page i want to render css with the help of if else logic based on cookie value stored in variable at code behind.
suppose in my .cs code behind i store the cookie value like strCountryCookie="GB" and in my aspx page i am trying to render css using if else logic based on cookie value stored in variable.
so here is the way i am trying.
<%
if(strCountryCookie=="DE")
{ %>
#acloginpod {
width:380px;
background:#ebebeb url(../images/acloginpodbg.gif) repeat-x;
border:1px solid #d3d3d3;
-webkit-border-radius:7px;
-moz-border-radius:7px;
}
<% } else { %>
it is showing error. so i am not being able to figure out how to render it based on cookie value using if else logic. so please guide me with concept. thanks
Like others said, you can't use server-side code in CSS. What you did is almost correct, if you make sure the string is accessible from the code behind:
protected string strCountryCookie = "GB";
and then fix your statement
<head runat="server">
<title>Test</title>
<% if (strCountryCookie == "GB")
{ %>
<style type="text/css">
#acloginpod {
width:380px;
background:#ebebeb url(../images/acloginpodbg.gif) repeat-x;
border:1px solid #d3d3d3;
-webkit-border-radius:7px;
-moz-border-radius:7px;
}
</style>
<%} %>
Although this will get rather ugly quick... especially if you add a bunch of countries.
Another option is to put all the custom styles into its own style sheet and then dynamically load up the style sheet based on the cookie. You get the benefit of the style sheet being cached in this case:
<link id="_countryStyleSheet" rel="stylesheet" type="text/css" runat="server" />
And then load the style sheet in your code behind:
_countryStyleSheet.Href = String.Format("~/styles/{0}.css", strCountryCookie);
In this example, the style sheet would be named GB.css, etc.
You can't use any code in CSS files.
you can put your css into a separate file and then include it or not in the header based on your condition.
approach that I prefer in such cases is to include ALL css markup on each page, but rather assign my elements with different classes based on condition. For you that would mean to use a class .acloginpod instead of id and then assign element with this class only when country is 'DE'.
or if you want different styles for different countries then define element class as following:
">
and in your css define different classes like mydiv-DE or mydiv-GB
I am trying to display an image from my database. I have an generic handler to display the image. But my problem is that it doesn't get called. My code for calling the handler is
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
where id is a number and ShowImage.ashx is the handler. The breakpoints in .ashx file doesn't get hit either. I am new to asp.net. So any help would be highly appreciated.
In this cases the steps that you need to follow is to see how the html is rendered.
So, right click on the html page, and "view page source".
There locate the point that the ShowImage.ashx is called, and see if the full rendered path is correct.
From there you simple correct the path.
Additional you can use the browser tools to see what browser looks for, and if he finds it or not. On google chrome for example you make right click, then inspect elements and then click on the network. There you can see with red, what files your page can not find, and you need to fix the path.
Check this sample Example code this might help you.
ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
HTTP Handler class Impliment in Img tag
</h1>
<h1>Id : 1</h1>
<img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />
<h1>Id : 2</h1>
<img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />
</div>
</form>
</body>
</html>
C# Examples (ImageHandler.ashx File) :
<%# WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
context.Response.ContentType = "image/jpeg";
if (context.Request.QueryString["id"] == "1")
{
context.Response.WriteFile("bamboo.jpg");
}
else
{
context.Response.WriteFile("palmtree.jpg");
}
}
public bool IsReusable {
get {
return false;
}
}
}
Here is live downloadable C# Examples and VB.Net Examples of this. Click Here...
How would I go about populating a database value to my html body background ?
Simply put, the HTML code is something like:
<body background="<%=session("userLogo")%>">
Update
Clarification of my question: Where in the code-behind, should I make the database call to populate the session("userLogo") value ?
Use this in your aspx:
body { background-image: url(<%= session("userLogo") %>); }
You can also put this in a css file (but then it has be an embedded resource and do remember to do performSubstitution = true)
Use <%= %>
<body background="<%= /* Code to retrieve value */ %>">
I'm building a web application and I have a question.
I want to display to the user running Random pictures in the Web Page.
how can I do this if it is possible.
thanks.
If you want to use a built-in control, you should look at the AdRotator. It will allow you to setup a XML file that lists all of your images that will be random displayed when the control renders on the page.
Control Usage:
<asp:AdRotator id="AdRotator1" runat="server" Target="_self"
AdvertisementFile="~/App_Data/Ads.xml"/>
Example XML File ( Ads.xml ):
<Ad>
<ImageUrl>~/Images/image1.jpg</ImageUrl>
<height>60</height>
<width>190</width>
<NavigateUrl>http://www.microsoft.com</NavigateUrl>
<AlternateText>Microsoft Main Site</AlternateText>
<Impressions>80</Impressions>
<Keyword>Topic1</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Images/image2.jpg</ImageUrl>
<height>90</height>
<width>90</width>
<NavigateUrl>http://www.wingtiptoys.com</NavigateUrl>
<AlternateText>Wingtip Toys</AlternateText>
<Impressions>80</Impressions>
<Keyword>Topic2</Keyword>
</Ad>
</Advertisements>
If your looking for something that can change the images client side (via JavaScript), there are a ton of solutions available. Here is an example of using the jQuery.Cycle plugin.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="jQueryRotateImages.aspx.cs" Inherits="DevOne.jQueryRotateImages" %>
<!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>jQuery Rotate Images - Cycle Plugin</title>
<style type="text/css">
.slideshow { height: 232px; width: 232px; margin: auto; }
.slideshow img { padding: 15px; border: 1px solid #ccc; background-color: #eee; }
</style>
<!-- include jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- include Cycle plugin -->
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="slideshow" class="slideshow" runat="server">
</div>
</form>
</body>
</html>
And here is how you can add your images dynamically in your code behind.
using System;
using System.Web.UI.HtmlControls;
namespace DevOne
{
public partial class jQueryRotateImages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach1.jpg", Width = 200, Height = 200});
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach2.jpg", Width = 200, Height = 200 });
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach3.jpg", Width = 200, Height = 200 });
}
}
}
pseudocode:
//On Page Load do this:
//create list of images from whatever your image source is
//generate a random number between 0 and `ImageList.Length - 1`
//assign the url from the image at the random index to the ImageUrl property of your Image control
If you simply want to pull a random image from a folder on the website, you could do something like the following:
string[] files = Directory.GetFiles(Server.MapPath(#"/images/"));
Random r = new Random();
string imageName = files[r.Next(files.Length);
// ... Code to display image.
However, you've really given sparse information of what you're trying to accomplish, such as where the images are coming from. This would be a very generic solution.
The following blog of msdn explains all the basics about the Random()
MSDN Microsoft Developer Network: Random()
The basic about it is that the Random class selects a random number from an array. It depends on the ticks time. MSDN DateTime Ticks
The ticks are used basically to generate a random. Random can be used as: Suppose I am extracting data from database. It will be
var db = Database.Open("databasename")
var image = db.Query("SELECT * FROM Images").ToList();
var randomImage = image[new Random().Next(image.Count)]
And display the data of it.
I am having an issue with a custom control rendering its contents (child controls) outside of the tag which leads to runtime errors and issues. In an attempt to simplify things as much as I can, I created the control below but it has the very same issue. I have tried inheriting from Control, WebControl and CompositeControl all resulting in with the same problem. Guessing there is something obvious that I am doing wrong... Thanks for any help.
using System;
using System.Web.UI.WebControls;
namespace MyControls
{
public class TestControl : CompositeControl
{
protected override void CreateChildControls()
{
Controls.Clear();
Controls.Add(new Button() { Text = "TestControl!" });
ClearChildViewState();
}
}
}
Adding the control programmatically results in markup outside the forms tag. Adding the control via markup works correct.
protected void Page_Load(object sender, EventArgs e)
{
Controls.Add(new TestControl());
}
...
<body>
<form name="PageForm" method="post" action="default.aspx" id="PageForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTE5MDEwMTE5MWRkg0FopdvLhTPGxHkGm1xCCOVQz6A=" />
</div>
<div>
</div>
</form>
</body>
</html>
<span><input type="submit" name="ctl04$ctl00" value="TestControl!" /></span>
Adding the control through the Page.Form property will render the button inside the form.
Page.Form.Controls.Add(new Button() { Text = "TestControl!" });
However, since the button is not contained within a block, such as a <div>, you might have some layout issues with this button. Use ScarletGarden's approach.
This has nothing to do with your custom control. Your problem is caused by how you're adding the control to the page.
When you call Controls.Add in your page's Page_Load method, this is basically shorthand for:
Page.Controls.Add(new TestControl());
ie, You're adding the control at the end of your entire page's control hierarchy. When the page is rendered, your control is rendered after all the others - even after the closing </html> tag.
If you want your control to be rendered inside the form then you need to add it to the form's control hierarchy instead:
Form.Controls.Add(new TestControl());
If you need even more fine-grained positioning, then you need to put a placeholder (or div or span etc) on your page in the required position and add your control to that, as in ScarletGarden's answer.
Your control seems ok, I think you have a problem with adding your control to your page,
Add a placeHolder to your page,
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="placeHolder" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
and then add your composite control to this placeholder's controls collection like that :
TestControl testCtrl = new TestControl();
placeHolder.Controls.Add(testCtrl);