jsf messages: adding link - html

Currently in JSF, all HTML contained within a message (rich:messages tag) is escaped and just shows up as the markup. For example, in my backing bean, I have:
createMessage("Title created successfully with product number: " + product.getProductNumber() + ".");
where createMessage() is just a helper function that adds a new Message to the faces context and is then viewable in my rich:messages tag.
When this message is created, my message simply shows up with the escaped HTML:
Title created successfully with product number: 1234.
Is there any way to avoid this and just provide an actual link in the message instead?
Thanks in advance
~Zack

A quick solution is to create a new renderer.
I've done this for h:messages as I wanted to separate the messages of different severities into separate divs. If you never want to use the default renderer then it's a good option.
The standard class that you would overwrite/extend is:
public class MessagesRenderer extends HtmlBasicRenderer
You would just use a ResponseWriter that doesn't escape the text. The concrete class is the HtmlResponseWriter which escapes the text. You could extend this and overwrite the
public void writeText(Object text, String componentPropertyName)
so that it doesn't use HtmlUtils.
Then just add your new renderer to faces-config.xml
<render-kit>
<renderer>
<component-family>javax.faces.Messages</component-family>
<renderer-type>javax.faces.Messages</renderer-type>
<renderer-class>com.mypackage.MessagesRenderer</renderer-class>
</renderer>
</render-kit>

It sounds like you need to create your own version of rich:messages that has an escape attribute, like h:outputText, so you can disable HTML escaping.

If you're using jquery you can unescape the xml characters:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$(".esc").each(function(i) {
var h = $(this).html();
h = h.replace(/</gi, "<");
h = h.replace(/>/gi, ">");
$(this).html(h);
});
});
//]]>
</script>

Related

Adding html elements to page with MVC Razor pages

On the html for my page I have a <script id="pagedata"></script> element which I would like to add an element to only if a certain partial is rendered. In my layout.cshtml I have the following:
#if (Brand != null)
{
#Html.Partial("_UseApp");
}
And in my _UseApp.cshtml:
#{
var iosAppUrl = // retrieve iosLink from our CRM database
var androidUrl = // retrieve android link from our CRM database
// Here I want to add the above variables to the <script id=pagedata> in the html page. Something
like this:
PageData.AddPageData("appstore", iosAppUrl);
PageData.AddPageData("playstore", androidUrl);
I cannot work out how to do this - I set breakpoints in the UseApp.cshtml file and the file is being called, but I don't know how to add these script elements. I don't want to just add them into the layout file because I want to keep the app logic separate. Can anyone help? Thanks
My approach to this would be to use jQuery, as reading HTML elements in C# is rather difficult.
In the script below, it checks if the HTML exists, and if it does, we will assign an attribute to it. The second argument in attr() will be your link, note that you can use C# to get the value from your Db, by using the model or ViewBag.
#section Scripts{
<script>
$(document).ready(function () { // on ready
if ($("#replaceWithYourId").length) { // check if ID exists
$("#pagedata").attr("data-playstore", "link") // use jQuery attr method.
}
});
</script>
}

HTML.TextAreaFor - removing html tags for display only

In an MVC application I have to use #HTML.TextAreaFor to display some text from a database, the trouble is sometimes that text may have HTML tags within it and I can't see a way to remove those for display only.
Is it possible to do this in the view (maybe with CSS?) without having to strip the tags in the controller first?
EDIT
The data coming from the controller contains html tags which I do not want to remove, I just don't want to display them
Normally I would use #HTML.Raw but it has to work in a #HTML.TextAreaFor control.
If you want to decode Html returned from the Controller you can use the following JavaScript method:
This method decodes "Chris&apos; corner" to "Chris' corner".
var decodeEntities = (function () {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
You can do this by using a razor code in your view.
#Html.Raw(HttpUtility.HtmlDecode(Model.Content))
if I set Model.Content to this string "<strong>This is me</strong><button>click</button>", the code above will render it like HTML code and will have a strong text next to a button as an output like the image below:
There's some nice rich text editors libraries like CK Editor, Quill, or TinyMCE that can display HTML while still maintaining the editor capabilities of being a text editor. All of these libraries have capabilities of being read-only as well if that's necessary.
Example from Quill -
Sorted this by changing TextAreaFor toTextBoxFor and setting a formatted value.
#Html.TextBoxFor(x => Model.MyItem, new { #class = "form-control", #required = "true", Value = Regex.Replace(Model.MyItem, "<.*?>", String.Empty) })

Allow using some html tags in MVC 4

How i can allow client to use html tags in MVC 4?
I would like to save records to the database and when it extract in view allow only some HTML tags (< b > < i > < img >) and others tags must be represented as text.
My Controller:
[ValidateInput(false)]
[HttpPost]
public ActionResult Rep(String a)
{
var dbreader = new DataBaseReader();
var text = Request["report_text"];
dbreader.SendReport(text, uid, secret).ToString();
...
}
My View:
#{
var dbreader = new DataBaseReader();
var reports = dbreader.GetReports();
foreach (var report in reports)
{
<div class="report_content">#Html.Raw(report.content)</div>
...
}
}
You can replace all < chars to HTML entity:
tags = tags.Replace("<", "<");
Now, replace back only allowed tags:
tags = tags
.Replace("<b>", "<b>")
.Replace("</b>", "</b>")
.Replace("<i>", "</i>")
.Replace("</i>", "</i>")
.Replace("<img ", "<img ");
And render to page using #Html.Raw(tags)
If you are trying some property of your view model object to accept Html text, use AllowHtmlAttribute
[AllowHtml]
public string UserComment{ get; set; }
and before binding to the view
model.UserComment=model.UserComment.Replace("<othertagstart/end>",""); //hard
Turn off validation for report_text (1) and write custom HTML encoder (2):
Step 1:
Request.Unvalidated().Form["report_text"]
More info here. You don't need to turn off validation for entire controller action.
Step 2:
Write a custom html encoder (convert all tags except b, i, img to e.g.: script -> ;ltscript;gt), since you are customizing a default behaviour of request validation and html tag filtering. Consider to safeguard yourself from SQL injection attacks by checking SQL parameters passed to stored procedures/functions etc.
You may want to check out BBCode BBCode on Wikipedia. This way you have some control on what is allowed and what's not, and prevent illegal usage.
This would work like this:
A user submits something like 'the meeting will now be on [b]monday![/b]'
Before saving it to your database you remove all real html tags ('< ... >') to avoid the use of illegal tags or code injection, but leave the pseudo tags as they are.
When viewed you convert only the allowed pseudo html tags into real html
I found solution of my problem:
html = Regex.Replace(html, "<b>(.*?)</>", "<b>$1</b>");
html = Regex.Replace(html, "<i>(.*?)</i>", "<i>$1</i>");
html = Regex.Replace(html, "<img(?:.*?)src="(.*?)"(?:.*?)/>", "<img src=\"$1\"/>");

Word having single quotes search from xml file using jquery issue

Hi I need to parse XML file using jquery. I created read and display functionality. But when a word having single quote not working.
My XML is like this
<container>
<data name="Google" definition="A search engine"/>
<data name=" Mozilla's " definition="A web browser"/>
</ container>
using my jquery code I can read definition of Google. But I can't read Mozilla's definition due to that single quotes. This is my jquery code.
var displayDefinition = function(obj){
$.get("definitions.xml", function(data){
xml_data1.find("data[name^='"+obj.innerHTML+"']").each(function(k, v){
right=''+ $(this).attr("Defination") + '';
}
}
$(".result").append(right);
}
Any body knows the solution for this please help me.
Thanks
jQuery deals with single quotes very well. the structure of your function looks really wild though. I changed it a big assuming you want to create a function that can display the definition based on passing it a name: http://jsfiddle.net/rkw79/VQxZ2/
function display(id) {
$('container').find('data[name="' +id.trim()+ '"]').each(function() {
var right = $(this).attr("definition");
$(".result").html(right);
});
}
Note, you have to make sure your 'name' attribute does not begin or end with spaces; and just trim the string that the user passes in.

How to display code in plain text?

I want to display bare code on an HTML page, I tried this:
<script>
function getSize() {
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
The above JavaScript code is some code entered by the user. I can't figure out to show this bare code on the html page without being interpreted and screwed up by the browser.
How do I display bare code on an HTML page?
I'm not quite clear on the specifics of the issue, as pre tags should, in general, do the trick, but here's an alternative tag:
<xmp>[Code can be displayed here]</xmp>
If you're using a server-side language, though, I'd suggest converting to HTML entities before outputting, then using CSS to style it.
As well, be sure if you're accepting user input that any JavaScript is being filtered and never executed.
You can use the <pre> and <code> tags to display formatted code. But to prevent the code from executing and not displaying you'll need to convert the text to character entities. > becomes >, < becomes &lt, etc.
You could do this by using PHP, for example:
<?php echo htmlentities('function getSize() { var myFSO = new
ActiveXObject("Scripting.FileSystemObject");
var filepath =
document.upload.file.value; var
thefile = myFSO.getFile(filepath);
var size = thefile.size; alert(size
+ " bytes"); }'); ?>
As your system relies on user input, you might have to rely on AJAX to actually process the user input and convert it to HTML entities.
Use the <code></code> tag, and use javascript or your sever-side scripting language
Dump it into a textarea and render it like a div tag
This is a bit of a hack and parlor trick, but it works.
Get bare code rendered onto an HTML page is to place it in a text area and remove all the formatting around the textarea so it looks like a <div> tag:
Code:<br>
<textarea style="border: none;width:400;height:200;background-color:lightgrey;">
#include<iostream>
using namespace std;
class Box{
public:
int mymethod(){ cout << "is method"; }
};
int myfunction(){ cout << "is function"; }
int main(){
Box b;
b.mymethod();
myfunction();
}
</textarea>
<br>
Output:
<pre>is methodis function
</pre>
The above html code should render like this on the page:
What I've done is invalid HTML, it only works because customary error handling happens to handle it this way. You shouldn't put unescaped angle brackets in the content of a <textarea>. You get undefined behavior depending on how the browser chooses to interpret your textarea tag.
The most reliable method is to htmlencode the code to be displayed on the page.
For example
< into &lt
space into &nbsp
etc.