How to get css styles in code behind asp.net - c#

I need to get css styles from code behind in asp.net c#, haven't found solution on the web, is it possible to get it directly from styles.css file or do I need to workaround?
I'm using themes in my web app, but I also need to do some server processing and I need colours from ccs files, which are different for each user of course:s

You should be able to retrieve the current styles with the following approach:
var targetElement = document.getElementById("myFancyElement");
var currentStyles = window.getComputedStyle(targetElement, null);
var color = currentStyles["color"];
document.getElementById("myCurrentColor").value = color;
The next step would be to post that color value back to the server. Which could either get posted as json with an XHR request, or simply set as a form value via a hidden input element, like so:
<input type="hidden" runat="server" name="myCurrentColor" id="myCurrentColor" />

Cs file
protected void Button1_Click(object sender, EventArgs e)
{
Panel1.CssClass = "RedBackground";
Panel1.Style.Add("font-size", "200%");
/// get value back
string pvalue = Panel1.Attributes["class"] ;
or
btn_4.Attributes.CssStyle["property"]
}
Html File
<style type="text/css">
.RedBackground
{
background-color: Red;
}
<asp:Panel ID="Panel1" runat="server">
Hello
</asp:Panel>

Related

asp.net C# how to programmatically change body background-image on Page_Load

I'm trying to make simple webpage here is my body in HTML code
<body runat="server" id="BodyTag" style="height: 1171px; width: 1148px;">
<form id="form1" runat="server">
On Page_Load in my Form.aspx.cs file i want to generate random number from 1 to X
where X is the number of files in a specific folder(folder containing images) then i want the body background image to be this random generated number as long as the image names in the folder are 1,2, ... , ... Here is my code
protected void Page_Load(object sender, EventArgs e)
{
string path = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos";
int countF = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
Random rand = new Random((int)DateTime.Now.Ticks);
int n = rand.Next(1, countF);
BodyTag.Style["background-image"] = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos/" + n.ToString() + ".jpg";
}
body background image does not change, it stays white and i dont understand why.Please do not hesitate to ask more information if you need
This is better achieved with css. Since you need a way to do it from code, the easiest option that comes to my mind is do it with generated Javascript
Javascript
<script type="text/javascript">
document.body.style.background = "url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
document.body.style.backgroundRepeat = 'no-repeat';
</script>
Applying it to your code
protected void Page_Load(object sender, EventArgs e)
{
string script = "<script type=\"text/javascript\">
document.body.style.background = \"url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
document.body.style.backgroundRepeat = 'no-repeat';
</script>\";
ClientScript.RegisterClientScriptBlock(this.GetType(), "background-changer-script", script);
}
This will just spill the Javascript to the bottom of your page and will be executed by the browser, changing the background as expected. Check the intellisense for Javascript and CSS for other background properties that can be set
You likely need to use a web relative URL:
BodyTag.Style["background-image"] = "http://localhost/FLUKSIKARTON/WebPhotos/BackGroundPhotos/" + n.ToString() + ".jpg";
Another approach would be to provide 1 CSS class per image and then switch which is being used:
CSS
.image1 {
background-image: url('/FLUKSIKARTON/WebPhotos/BackGroundPhotos/1.jpeg');
}
C#
BodyTag.CssClass = string.Format("image{0}.jpeg", n);

How do I use a C# string in my .aspx webpage?

I have passed a value through a url to a C# .net page using query string. The url of the page looks like this:
http://contoso.com/products.aspx?field1=value1
And in C#, I have this to catch it:
String myValue = Request.QueryString["field1"];
What im looking to do is use this value in the page, something like this:
<h1><%# Eval("myValue") %></h1>
How would I go about doing this? Obviously this HTML code doesn't work. I have exhausted some google searches on the subject so any information would be appreciated!!
You can either create a Property on your page and use code tags, or set the h1 tag as runat="server" and set the value like that.
Property:
public string MyString{ get; set; }
public void Page_Load(object sender, EventArgs e)
{
MyString = Request.QueryString["field1"];
}
Then in your markup:
<h1><%= MyString %></h1>
Alternatively, using the runat="server" method on the h1 tag:
Markup:
<h1 id="myH1" runat="server"></h1>
Code:
myH1.InnerText = Request.QueryString["field1"].ToString();
Try to add runat="server" and id to your h1 tag, so you can use it in cs-file.
HTML:
<h1 id="myHeader" runat="server"></h1>
CS:
myHeader.InnerText = myValue;
In your aspx file, you can define a text field like so:
<h1 Id="label" runat="server"/>
Then, in your code behind file add:
label.InnerText = Request.QueryString["field1"];

How to find header control of repeater in c# .net?

I am working on asp.net c# . I am trying to find the header control in c# . But I am getting object not set to an instance of an object . My code is
public void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
HtmlGenericControl ulSubNav2 = (HtmlGenericControl)e.Item.FindControl("da-sliders");
ulSubNav2.Style.Add("background", "transparent url('DesktopModules/DNAiusParallelSlider/Images/waves.gif') repeat 0% 0%");
ulSubNav2.Style.Add("width", "100%");
ulSubNav2.Style.Add("height", "400px");
}
}
relevant HTML Code
<HeaderTemplate>
<div id="da-sliders" class="da-slider" OnItemDataBound="R1_ItemDataBound">
</HeaderTemplate>
this is because the system failed to find the control with the name you specified.
Try to add a "runat" tag to the div like this :
<div id="da-sliders" class="da-slider" OnItemDataBound="R1_ItemDataBound" **runat="server"**>
Now in your ItemDataBound you have access to the div item in the HeaderTemplate.

Change CSS class programmatically on load?

I have two pages, let's call them "receipts.com" and "business.receipts.com". Both link to a page on a different domain via Response.Redirect("http://receipts2.com/default.aspx?mode=")
where the "mode"-parameter is the referring page.
The recieving page should look in the query string, and choose a different CSS class according to the "mode"-parameter.
How is this accomplished? And is this the right way to do it?
Instead of swapping class names you can use the same class and different stylesheets.
There are two ways to handle stylesheets: client side and server side.
On the client side, you can parse the query string and disable stylesheets using: (document.getElementsByTagName("link")[i]).disabled = true;
On the server side, you can use themes or simply add a placeholder around the style declarations and show/hide them using codebehind that looks at Response.QueryString["mode"]:
<asp:PlaceHolder ID="placeHolder1" runat="server" Visible="false">
<link rel="stylesheet" href="/alternate.css" media="all" />
</asp:PlaceHolder>
and code behind in a master page somewhere:
if(Response.QueryString["mode"] == "blah")
{
placeHolder1.Visible = true;
}
You could use different Page-Themes:
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["mode"])
{
case "receipts.com":
Page.Theme = "DefaultTheme";
break;
case "business.receipts.com":
Page.Theme = "BusinessTheme";
break;
}
}
Of course you can also use the code above to apply different Css-Classes to controls.
You can use document.referrer instead of passing in the page via querystring.
When you say "The receiving page should look in the query string, and choose a different CSS class", what is that class going to be set against, ie the body or an element like p?
Plain Javascript
document.getElementById("MyElement").className = " yourClass";
jQuery
$("p").addClass("yourClass");
Perhaps you meant a css theme?
and then you could try
if (document.referrer == "blahblah")
document.write("<link rel='stylesheet' type='text/css' href='one.css' />)
else
document.write("<link rel='stylesheet' type='text/css' href='two.css' />)
Although I would recommend looking into jQuery
$.get(stylesheet, function(contents){
$("<style type=\"text/css\">" + contents + "</style>").appendTo(document.head);
});
u can do something like this
{
string hrefstring = null;
string mode = this.Page.Request.QueryString.Item("mode");
if (mode == "a") {
hrefstring = ("~/yourcss/a.css");
} else if (mode == "b") {
hrefstring = ("~/yourcss/b.css");
}
css.Href = ResolveClientUrl(hrefstring);
css.Attributes("rel") = "stylesheet";
css.Attributes("type") = "text/css";
css.Attributes("media") = "all";
Page.Header.Controls.Add(css);
}

How to send an xml serialized object from ASP.NET to Silverlight

On the button click on an ASP.NET page, I need to load a silverlight application, passing a serialized object from ASP.NET codebehind to MainPage.xaml.cs. How to do this?
Why not use WCF? This is a perfect fit for sending serialized objects. Also, WCF hosts well on IIS, so it works great with ASP. Here is a tutorial to get you started. You should be able to see clearly how to define a simply API that you can call from Silverlight. You just need to make your object part of a DataContract.
Do either of these help - http://www.silverlight.net/archives/videos/using-startup-parameters-with-silverlight or http://forums.silverlight.net/t/183963.aspx/1 ?
Some options for you, may help. You could use Javascript - silverlight.net on scripting Silverlight to reach inside the Silverlight object from your page.
Another option is to have the Silverlight object access the AspNet page to ask for it's xml using PageMethods. ( System.Web.Services.WebMethod) once it's loaded.
One option is to configure a Silverlight onLoad event in the <object> tag for your app:
<param name="onLoad" value="setInfo" />
Then use script to push the XML into your app (dynamically insert the XML onto the page from ASP.NET):
<script type="text/javascript">
function setInfo(sender) {
var msg = '<yourtag>your info here</yourtag>';
sender.getHost().content.Page.SetInfo(msg);
}
</script>
To allow script to call your app, configure as follows:
public MainPage()
{
HtmlPage.RegisterScriptableObject("Page", this);
InitializeComponent();
}
[ScriptableMember]
public void SetInfo(string xml)
{
// do stuff
}
Register onLoad param in your Silverlight <Object> tag:
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
<param name="source" value="ClientBin/MySlApp.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<param name="onLoad" value="onSilverlightLoad" />
</object>
and register <Script>
<script type="text/javascript">
function onSilverlightLoad(sender, args)
{
var mySlControl = sender.getHost();
mySlControl.content.Communicator.MyDeserializer("SerializedObjectString")
}
</script>
In your Silverlight app register `Communicator' object so it is the app itself:
namespace MySilverlightApp
{
public MySilverlightApp()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Communicator", this);
}
}
and create de-serialization function decorated with [ScriptableMember]:
[ScriptableMember]
public void MyDeserializer(string _stringPassedFromHtmlDocument)
{
//deserialize _stringPassedFromHtmlDocument
}
I have above working in one of Sharepoint projects utilising Silverlight webpart. Serialized object is however rendered into HTML so not sure if that will work for your Button.Click() requirement. One thing though should you go down this route: I encountered many many many issues when trying XML serialization and found JSON to be better alternative.
In your MainPage.xaml.cs, define a property getter/setter for whatever object type you need passed.
In your ASP.NET page button click handler, set the property to the serialized object.
If you need this to maintain the serialized object after the page lifecycle finishes, simply change the property setter in MainPage.xaml.cs to persist the serialized object across page lifecycles.
Hope this helps.
Pete
There are two possible paths here:
1) When the button is pressed, the page posts back to the server, gathers some information, serializes it into XML, shows the silverlight component, which then loads the serialized XML.
2) When the page is loaded, the XML data is available. Pressing the button simply shows the silverlight component and asks it to load the XML data.
Scenario 1
Here are the steps that you need to take for scenario 1.
1) Add the silverlight component to the page and embed it in a container (div, table, whatever you like) that is set to runat server. Note that we also specify an onload param to fire a specific event when the silverlight object has finished loading:
<div id="divDiagram" runat="server">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
id="objDiagram">
<param name="onLoad" value="RefreshDiagram" />
</object>
</div>
2) In your code-behind, hide this container until the button is pressed. For example:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
divDiagram.Visible = false;
}
}
void Button1_Click(object sender, EventArgs e)
{
divDiagram.Visible = true;
}
3) Add a hidden input to hold the serialized data:
<input type="hidden" id="txtSerializedData" runat="server" />
4) Set the contents of this input on the button click:
txtSerializedData.Value = "some serialized data";
5) Modify the silverlight components code to expose the control to javascript:
public MainPage()
{
InitializeComponent();
System.Windows.Browser.HtmlPage.RegisterScriptableObject("DiagramPage", this);
}
6) Add a method to the silverlight control that can be called from javascript (this is the ScriptableMember attribute) to get the serializable content and work with it:
[System.Windows.Browser.ScriptableMember()]
public void RefreshDiagram()
{
// Fetch the hidden input control from the page
var serializedElement = System.Windows.Browser.HtmlPage.Document.GetElementById("txtSerializedData");
// Then fetch its value attribute
var sSerializedData = serializedElement.GetAttribute("value");
// Finally, do something with sSerializedData
}
7) Finally, add the javascript method to the page that is fired when the silverlight control is loaded:
<script type="text/javascript">
function GetDiagramPageContent() {
/// <summary>This method retrieves the diagram page object content</summary>
// Exceptions are handled by the caller
var oObject = document.getElementById('objDiagram');
if (oObject) {
return oObject.Content;
} else {
return null;
}
}
function RefreshDiagram() {
try {
var oContent = GetDiagramPageContent();
try {
// If we don't have content or a diagram page, bail
if ((oContent == null) || (oContent.DiagramPage == null)) {
return;
}
} catch (ex) {
return;
}
// Now ask the control to refresh the diagram
oContent.DiagramPage.RefreshDiagram();
} catch (ex) {
alert('Javascript Error (RefreshDiagram)\r' + ex.message);
}
}
</script>
Scenario 2
Scenario 2 is very similar to scenario 1, with the following changes:
1) Do not include the onLoad param in the silverlight object. Instead, call the RefreshDiagram javascript method from the client-side button click.
2) Do not show or hide the containing div in code-behind. Instead, use the style attributes to control the visibility:
<div id="divDiagram" runat="server" style="visibility: hidden; visibility: visible">
and in the javascript button click event:
var oDiv = document.getElementById("divDiagram");
oDiv.style.visibility = "";
oDiv.style.display = "";
3) Load the hidden text box in pageload instead of on the server-side button click.
This might help
Passing Objects between ASP.NET ans Silverlight Controls
best regards
You can use this thing called SilverlightSerializer by Mike Talbot

Categories