I want to edit programmatically css file using asp.net's code behind, furthermore I tried some commands but without results.
to explain my situation: I should modify file.css (.class1 exist) from file.aspx.cs. For example add this proprety :
.class {backgroud-color:grey}
I made this:
<link href="file.css" rel="stylesheet" id="boxcss" runat="server" />
and in the code behind:
string iframe = "iframe{border-radius:300px}";
boxcss.Attributes.Add("class",iframe);
thanks for your help
You can use the following code to add style attributes to the existing .class1 selector or to create a new .class2 selector:
Style class1 = new Style();
class1.BackColor = Color.Orange;
Header.StyleSheet.CreateStyleRule(class1, null, ".class1");
Style class2 = new Style();
class2.BorderColor = Color.Red;
class2.BorderStyle = BorderStyle.Solid;
class2.BorderWidth = Unit.Pixel(5);
Header.StyleSheet.CreateStyleRule(class2, null, ".class2");
However, the Style class does not give access to border-radius. You can add that style attribute to the Header with the help of a Literal control:
Literal iframeStyle = new Literal();
iframeStyle.Text = "<style>iframe { border-radius: 300px; }</style>";
Header.Controls.Add(iframeStyle);
Note: The head tag must have the runat="server" attribute to be accessible in code-behind:
<head runat="server">
Related
I want to allow all Alpine JS components (x-data, x-init, etc.) as attributes for all HTML tags in TinyMCE 4.
I tried to add them via a rule for extended_valid_attributes in different ways, but everything fails. Either they are still stripped from the code or they become valid, but all other attributes are then stripped.
Here are some examples of what I already tried, most of it I found in answers to other tinyMCE questions here (e.g. TinyMCE 4 - add custom styles/classes/attributes to any HTML tag) and read in the tinyMCE docs (https://www.tiny.cloud/docs-4x/configure/content-filtering/#extended_valid_elements, https://www.tiny.cloud/docs-4x/configure/content-filtering/#controlcharacters):
$alpineAttributes = 'x-data|x-init|x-show|x-text|x-html|x-model|x-for|x-transition|x-effect|x-ignore|x-ref|x-cloak|x-teleport|x-if|x-id';
$settings['extended_valid_elements'] = '*['. $alpineAttributes .']';
-> select all elements via *: doesn't work, the alpine attributes still get stripped
$settings['extended_valid_elements'] = '#['. $alpineAttributes .'],div,a,p';
-> here at least the attributes don't get stripped anymore for div, a and p tags, but all other attributes that would normally be allowed for each of those three now get stripped, because the list of allowed attributes doesn't get extended but overriden with my attributes.
$settings['extended_valid_elements'] = '#['. $alpineAttributes .'],*';
-> doesn't work, the alpine attributes still get stripped
$settings['extended_valid_elements'] = '#['. $alpineAttributes .']';
-> doesn't work, the alpine attributes still get stripped
Is there really no way to just EXTEND the list of allowed attributes for each element instead of completely overriding it with my rules in extended_valid_elements?
We can solve this issue using different strategy. We can change Alpine prefix from x- to data-x-.
As per the HTML standard x-data, x-init ... are not valid "custom attributes". The attributes need to have prefix data-.
TinyMCE allows data-* custom data attributes by default, without having to specify them in any rules. So instead of forcing Alpine prefixes on TinyMce we can simply change the prefix on Alpine, using Alpine.prefix("data-x-").
Demo: on codepen
<!DOCTYPE html>
<html>
<head>
<style>
#output {
font-family: monospace;
font-size: 0.9em;
color: rgb(83, 23, 23);
}
</style>
</head>
<body>
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script src="https://unpkg.com/alpinejs#3.8.1/dist/cdn.min.js"></script>
<script>Alpine.prefix("data-x-");</script>
<p data-x-data="{date:'Date: '+ new Date().toISOString()}" data-x-text="date">date place holder</p>
<textarea id=editor>Tiny!</textarea>
<input type="button" id="btn" value="Show editor HTML content" />
<div id=output></div>
<script type="text/javascript">
let content = `<br><p data-x-data="{date: 'Date: '+new Date().toISOString()}" data-x-text="date">date place holder</p>`;
tinymce.init({
selector: '#editor',
schema: 'html5',
setup: function (editor) {
editor.on('init', function (e) {
editor.setContent(content);
setTimeout(() => Alpine.initTree(editorDOM()), 200);
});
}
});
btn.onclick = function () {
output.innerText = tinyMCE.activeEditor.getContent();
}
function editorDOM() {
return (editor_ifr.contentWindow
? editor_ifr.contentWindow.document
: editor_ifr.contentDocument).body;
}
</script>
</body>
</html>
The alpine x-text attribute works inside the editor as well, and it shows current date. This is because TinyMce allows our data-x-text attribute.
Note:
In the demo I've used TinyMce latest version 5. It works on version 4 as well. Tested using following CDN:
<script src='https://cdn.tiny.cloud/1/no-api-key/tinymce/4/tinymce.min.js'></script>
TinyMCE doesn't work on StackOverflow because of iframe restrictions that is why I've provided the codesandbox link.
I am using draft js to create email templates in a reactJs application.
I implemented custom block types and with css I was able to align my columns properly (left, center, right). I used RichUtils to toggle block type.
However, my problem is when I am exporting the editor state into html, only the tags are exported, but I need the style too, so that the text-align style remains the same.
I use stateToHtml from draft-js-export-html when exporting the html.
I was also thinking about adding custom attributes, but I was not successful with it yet.
I appreciate every answer and thank you for the help in advance.
you can try this way:
import { ContentState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
const currentContent = this.state.editorState.getCurrentContent();
return draftToHtml(convertToRaw(currentContent));
As an extension on #ArtemZubarev , there will be a problem when exporting it to html because it will contain no styles. So this requires 2 answers
How to get state to html: credits to #ArtemZubarev
import { ContentState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
const currentContent = this.state.editorState.getCurrentContent();
return draftToHtml(convertToRaw(currentContent));
However, this will return unstyled elements, for example: <h1>Hello World</h1>.
This raises the question: How to keep the styling?
Option 1: CSS
Option 2: Create a render function that will inject the styles as inline
private injectHTML = (html?: string) => {
return `<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
${
html
}
</body>
</html>`
}
Is there a way to add white space in MVC while using variables? for example foreach(item in collection) {#item #item}. How to make a blank space something like " " in it?
You can use pre tag , which defines preformatted text.
foreach(item in collection) {
<pre>#item #item</pre>
}
have you tried this can be repeated i.e. you can do line breaks with <br />
In my application I have used a space after the link's name ("Details ") as shown here
#Html.ActionLink("Details ","Details", new { Variable_ID = item.VIP_ID})
#Html.ActionLink("Edit", "Edit", new { Variable_ID = item.VIP_ID })
so my links will look like this: Details Edit, instead of DetailsEdit.
You can also put a separation bar like this "Details | ", so you can have
Details | Edit
<span> </span>
Insert " " to add more blank spaces
//This will work for sure, as MVC C# using razor syntax then you just need to put space between those two only
foreach(var item in collection) {
<span>#item #item</span>
}
If you wish to add single space between item:
foreach(item in collection)
{
<p>#item #item</p>
}
But you will have better flexibility if you wrap it in a HTML element like div or span,
and then add padding/margin to the element using CSS.
foreach(item in collection)
{
<div class="user-defined-classname">#item</div>
<div class="user-defined-classname">#item</div>
}
In CSS
.user-defined-classname{
padding-left|right|top|bottom: 10px
}
Suggestion:
The "Views" folder is specifically meant to just contain your view files (i.e. .cshtml files).
Try adding your CSS file to a folder in the root of the ASP.NET project. Often, this folder is named "Content", but you can rename it as "Styles" or something else. Then you can load your CSS file from within a view using a link tag:
<link href="~/Content/styles.css" rel="stylesheet" type="text/css" />
This may help.
One more variant:
#(string.Format("{0} {1}", item, item))
In trying to fine-tune the appearance of my Web API page, I'm making changes to CSS classes, and adding new classes, to \Content/Site.css, yet they do not alter the appearance of the page as they should, even when I append "!important" to specific rules.
For example, I added a horizontal rule to the page, which does show up, but quite unobtrusively (with a faint, barely discernible line). So I added this .css class to Site.css:
hr {
border: 0;
height: 1px;
color: navy;
background: #333;
}
...which works just fine in another project, but doesn't in this one. The line remains faint even when I append "! important" to the "height" rule there:
height: 1px !important;
I tried right-clicking the page at runtime and selecting "Reload Page" but that made no difference, either.
Other CSS changes (margins and paddings) are not having any effect, either; this is just one specific case whose resolution should work for all of them.
What do I need to do to get modified/added CSS rules to be applied?
UPDATE
Even when I, acquiescing to Algernop K's suggestion, change the code from this:
. . .
builder.Append(string.Format("<h1 style=\'margin-left:16\'>Available PRO*ACT Reports for <span style='color: #000080;'>{0}</span></h1>", _unit.ToUpper()));
builder.Append("<p style='margin-left:16;'>(Click any link below to download the Excel spreadsheet file to your computer)</p>");
builder.Append("</div>");
builder.Append("<div class=\"row\">");
builder.Append("<div class=\"col-md-12\">");
builder.Append("<hr />");
. . .
...to this:
. . .
builder.Append(string.Format("<h1 style=\'margin-left:16; margin-top:48;\'>Available PRO*ACT Reports for <span style='color: #000080;'>{0}</span></h1>", _unit.ToUpper()));
builder.Append("<p style='margin-left:16;'>(Click any link below to download the Excel spreadsheet file to your computer)</p>");
builder.Append("</div>");
builder.Append("<div class=\"row\">");
builder.Append("<div class=\"col-md-12\">");
builder.Append("<hr style=\'size:4;\' />");
. . .
...(adding "; margin-top:48;" to the h1 element, and "size" to the hr), no change is evident.
UPDATE 2
A "funny" thing happened on the way to the Inspecting of Elements. As Chris W suggested, I right-clicked the hr element on the page, but it's so miniscule that I may have got a different element to inspect. Nevertheless, an err msg in the console may be revealing the basic problem - there it says, "bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires jQuery"
UPDATE 3
Should I explicitly add my \Content\Site.css file to the html? I tried dragging it from Solution Explorer below the lines shown above, hoping it would generate the correct code, but instead it gave me:
C:\Projects\ProActWebReports\ProActWebReports\Content\Site.css
...and a prompt to add "'System.Security.Policy.Site' and all other references in file"
Note that I have a related question here
UPDATE 4
FWIW, here's the entire (relevant) code that builds up this html:
namespace PlatypusWebReports.Controllers
{
[RoutePrefix("api")]
public class LandingPageController : ApiController
{
private string _unit;
[Route("{unit}")]
public HttpResponseMessage Get(string unit)
{
_unit = unit;
string beginningHtml = GetBeginningHTML();
string deliveryPerformanceHtml = GetDeliveryPerformanceHTML();
string fillRateHtml = GetFillRateHTML();
string priceComplianceHtml = GetPriceComplianceHTML();
string produceUsageHtml = GetProduceUsageHTML();
string endingHtml = GetEndingHTML();
String HtmlToDisplay = string.Format("{0}{1}{2}{3}{4}{5}",
beginningHtml,
deliveryPerformanceHtml,
fillRateHtml,
priceComplianceHtml,
produceUsageHtml,
endingHtml);
return new HttpResponseMessage()
{
Content = new StringContent(
HtmlToDisplay,
Encoding.UTF8,
"text/html"
)
};
}
private string GetBeginningHTML()
{
StringBuilder builder = new StringBuilder();
builder.Append("<html>");
builder.Append("<head>");
builder.Append("<title>");
builder.Append(string.Format("Available Reports For {0}", _unit));
builder.Append(_unit);
builder.Append("</title>");
builder.Append("<script src='https://code.jquery.com/jquery-1.12.2.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>");
builder.Append("<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet' />");
builder.Append("<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>");
builder.Append("</head>");
builder.Append("<body class=\"body-content\" style='margin-top:0;margin-left:60;margin-right:60;'>");
builder.Append("<div class=\"jumbotronjr\">");
builder.Append("<img src=\"http://www.Platypususa.com/wp-content/themes/Platypus/images/pa_logo_notag.png\" alt=\"Platypus logo\">");
builder.Append(string.Format("<h1 style=\'margin-left:16; margin-top:48;\'>Available Platypus Reports for <span style='color: #000080;'>{0}</span></h1>", _unit.ToUpper()));
builder.Append("<p style='margin-left:16;'>(Click any link below to download the Excel spreadsheet file to your computer)</p>");
builder.Append("</div>");
builder.Append("<div class=\"row\">");
builder.Append("<div class=\"col-md-12\">");
builder.Append("<hr style='color:red;height:12;' />");
builder.Append("</div>");
builder.Append("</div>");
// for beginning the row div
builder.Append("<div class=\"row\">");
return builder.ToString();
}
private string GetEndingHTML()
{
StringBuilder builder = new StringBuilder();
// for ending the row div
builder.Append("</div>");
builder.Append("</body>");
builder.Append("</html>");
return builder.ToString();
}
. . .
Everything is displaying basically as I want it to, it's just not allowing me to add the "gingebread" (adding margins, hrs, shadow around the used area)
UPDATE 5
Even though _ViewStart.cshtml points to Layout:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
...and _Layout.cshtml renders (supposedly) the Styles in the Content/css folder, which contains the Sites.css which I have been adding CSS styles madly to:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - PRO*ACT USA</title>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
</head>
<body>
<div class="container body-content">
#RenderBody()
</div>
#*#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")*#
#RenderSection("scripts", required: false)
</body>
</html>
...all that does nothing to add these styles I want. The only way seems to use inline styles:
builder.Append("<body style='margin-top:40;margin-left:60;margin-right:60;'>");
. . .
builder.Append("<hr style='border:0;height:1;background:#333;color:navy;' />");
The whole process could certainly be made much clea[n,r]er / more straightforward.
I used "chrome.tabs.insertCSS" to inject CSS into a page. I would like to add an option to the user to remove this css (with a button or something).
The question is then - how do I remove this css/js (programmatically) addition from the tab?
Instead of injecting styles automatically, manually create <style> element with some id, which you can later remove from the DOM.
Here is a snapshot from an extension that enables and disables link underlining through css:
//enable.js
var head = document.head;
var style = document.createElement("style");
var rules = document.createTextNode("a {text-decoration:underline !important;}");
style.type = "text/css";
style.id = "__link-highlighter";
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
head.appendChild(style);
//disable.js
if(document.getElementById("__link-highlighter")) {
document.head.removeChild(document.getElementById("__link-highlighter"));
}
I am injecting CSS rules into the body of <style> element because they are very small, if you need a lot of rules you should be able to create <link rel="stylesheet"> instead linking to chrome.extension.getURL("styles.css").