Bold Text in Html.FormatValue using Razor - c#

I want to have the following result. Username has to be bold:
Blabla Username Bla.
I have the Format in a ressource file:
Blabla {0} Bla.
And in the view I do the following:
#Html.FormatValue(User.Identity.Name, Resources.MyFormatString)
How can I make the Username bold and use Html.FormatValue? Or is there another method to achieve this?

You could simply change your resource to contain the bold-tag, strong-tag or a style.
Like "Blabla <b>{0}</b> Bla.".
[edit]
Indeed, checked Html.FormatValue for an escape functionality, did not see one, but apparently it does :)
In that case using #Html.Raw and string.Format will work.
#Html.Raw(string.Format(Resources.MyFormatString, "SomeName"))
(tested in MVC 5, but #Html.Raw is also available in 4)
Also a small note: storing HTML in resources is probably not the best idea, mixing UI & content.
[/edit]

I wanted to solve your example with including html tags, be safe with html characters in the resources, and safely include user input or html tags. My solution of your example is
#(Resources.MyFormatString.FormatWithHtml(
"<b>" + HttpUtility.HtmlEncode(User.Identity.Name) + "</b>"))
using my function FormatWithHtml
/// Encodes to MvcHtmlString and includes HTML tags or already encoded strings, placeholder is the '|' character
public static MvcHtmlString FormatWithHtml (this string format, params string[] htmlIncludes)
{
var result = new StringBuilder();
int i = -1;
foreach(string part in format.Split('|')) {
result.Append(HttpUtility.HtmlEncode(part));
if (++i < htmlIncludes.Length)
result.Append(htmlIncludes[i]);
}
return new MvcHtmlString(result.ToString());
}
One more example, this
#("Resource is safe to html characters <&> and will include |format tags| or any | user input."
.FormatWithHtml("<b>", "</b>", "<b id='FromUser'>" +HttpUtility.HtmlEncode("<a href='crack.me'>click</a>") +"</b>"))
will write to your razor page
Resource is safe to html characters <&> and will include format tags or any <a href='crack.me'>click</a> user input.

Related

Validate Razor template

How can I validate Razor template, which is used to render mail template.
string template = #"
My template
#if (Model.Condition { <span>is true</spaM> }"
I made two mistakes: missing closing bracket and wrong closing tag.
I need to validate it and known what should I fix (the best is to known in which line). I would like to use native Razor methods.
If I understand correctly, you want to be notified that the code you've written in the Template is invalid HTML.
If so, I'm afraid there is no easy way. The Template is purely producing text that you specify to go out to the response.
It may not even be HTML - could be JavaScript or a number of other outputs - it's just a string of text.
You may have a Template that produces the start of a table, another that produces the body, and another that produces the footer and end table tags. Each of these would produce invalid HTML on their own, but output one after the other would produce a valid HTML table. (That's a lot of produces there - sorry).
What would make it invalid is the parser of the HTML - i.e. the browser. You would only be able to validate your Template output when it is in a complete document that can then be parsed.
You mean ?
#{
string template = Model.Condition ? "My template <span>is true</span>" : "";
}
string MyString = string.empty;
#if(Model.Condition)
{
MyString ="<span>"+ "is true"+"</span>";
}

Decoding only certain HTML tags in ASP.NET MVC

I'm working with ASP.NET MVC 5 application. I have to output the HTML which a user has entered with some formatting. I store the HTML in the database as it is, i.e. without encoding, as it's adviced here, but before showing it I encode it using MS AntiXSS library. However, I have to output some tags as HTML, e.g. make text bold or italic. What's the best approach to do that, while keeping the application safe from XSS? The idea I have is to first encode the text using AntiXssEncoder and then replace the allowed tags with the usual characters using RegExp. I know that some tools exist for it, like HTML Purifier, but I haven't found anything for ASP.
Update:
I've decided to use something like
private static readonly Dictionary<string, string> allowedTags = new Dictionary<string, string>()
{
{"<p>", "<p>"},
{"</p>", "</p>"},
{"<strong>", "<strong>"},
{"</strong>", "</strong>"},
{"<em>", "<em>"},
{"</em>", "</em>"},
{"&nbsp;", " "},
{"
", "<br>"}
};
and then
StringBuilder text = new StringBuilder(AntiXssEncoder.HtmlEncode(item.Text, true));
foreach (var tag in allowedTags)
{
text.Replace(tag.Key, tag.Value);
}
Though I strongly dislike this solution since it lacks flexibility and I would have to manually insert each tag into the dictionary. Also, it doesn't support attributes, e.g. < p align="center" > would have to be a separate value. I guess I can replace the first part of the tag like
text.Replace("<p", "<p");
However, if some tag is called, for example, padding (I don't know all HTMl tags which exist or might appear), then it would work with it too, since its beginning will be replaced, thus turning it into a valid tag (which might be not closed, though).

Removing HTML from a string

I have a table (a Wijmo Grid). The column Log takes some text.
The user is allowed to write HTML in the text, because the same text is also used when mailed to make it look pretty and well styled.
Let's say the text is:
var text = "Hello friend <br> How are you? <h1> from me </h1>";
Is there any method or JSON.stringify() og HTML.enocde() i can/should use to get:
var textWithoutHtml = magic(text); // "Hello friend How are you? from me"
One of the problems is that if the text include "<br>" it break to next line i the row of the table, and it's possible to see the top-half of the second line in the row, witch doesn't look good.
var text = "Hello friend <br> How are you? <h1> from me </h1>";
var newText = text.replace(/(<([^>]+)>)/ig, "");
fiddle: http://jsfiddle.net/EfRs6/
As far as i understood your question you can encode the values like this in C#
string encodedValue= HttpUtility.HtmlEncode(txtInput.Text);
Note: here txtInput is the id of TextBox on your page.
You may try like this:
string s = Regex.Replace("Hello friend <br> How are you? <h1> from me </h1>", #"<[^>]+>| ", "").Trim();
You can also check the HTML Agility Pack
This is an agile HTML parser that builds a read/write DOM and supports
plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor
XSLT to use it, don't worry...). It is a .NET code library that allows
you to parse "out of the web" HTML files. The parser is very tolerant
with "real world" malformed HTML. The object model is very similar to
what proposes System.Xml, but for HTML documents (or streams).
<[^>]+>| /
1st Alternative: <[^>]+>
< matches the characters < literally
[^>]+ match a single character not present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
> a single character in the list > literally (case sensitive)
> matches the characters > literally
2nd Alternative:
matches the characters literally (case sensitive)

HTML encode string in MVC Razor except for one tag

I have a string which contains HTML in a Razor view.
var s = "A string.<br> It has <abbr>HTML</abbr>."
I want to HTML encode everything except for the <br>
s == "A string.<br> It has <abbr>HTML<abbr>."
This does not work:
#s.Replace("<br>", "<br>")
The strings come from a database of user created content and the only tags they should contain are <br>s, but in practice they might contain just about anything, and if they do I must keep it that way but display it in a safe way. Of course, the data should never have been saved this way to begin with, but it is, so I have to deal with it.
I can't just use Html.Raw() because I need to encode everything else. However, Html.Encode() encodes too much, converting "\r" to "
" etc. (Something must have been funny with the data I tested this on the first time, Html.Encode() does not seem to be the issue any more).
You can do it as follows:
#Html.Raw(Html.Encode(str).Replace("<br>", "<br>"))
We encode the string using Html.Encode after which we convert the encoded tag <br> back to the <br> tag and use #Html.Raw to output it without being encoded again.
This looks a little ugly to me, but it works.
var splitString = s.Split(new string[] { "<br>" }, StringSplitOptions.None);
foreach (string line in splitString)
{
#line<br>
}

ASP.NET MVC Html.Encode - New lines

Html.Encode seems to simply call HttpUtility.HtmlEncode to replace a few html specific characters with their escape sequences.
However this doesn't provide any consideration for how new lines and multiple spaces will be interpretted (markup whitespace). So I provide a text area for the a user to enter a plain text block of information, and then later display that data on another screen (using Html.Encode), the new lines and spacing will not be preserved.
I think there are 2 options, but maybe there is a better 3rd someone can suggest.
One option would be to just write a static method that uses HtmlEncode, and then replaces new lines in the resulting string with <br> and groups of multiple spaces with
Another option would be to mess about with the white-space: pre attribute in my style sheets - however I'm not sure if this would produce side effects when Html helper methods include new lines and tabbing to make the page source pretty.
Is there a third option, like a global flag, event or method override I can use to change how html encoding is done without having to redo the html helper methods?
HtmlEncode is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters.
I would go with your first option, and make it an extension method for HtmlHelper. Something like:
public static string HtmlEncode(this HtmlHelper htmlHelper,
string text,
bool preserveWhitespace)
{
// ...
}
You could use String.Replace() to encode the newlines and spaces (or Regex.Replace if you need better matching).
Using the style="white-space:pre-wrap;" worked for me. Per this article.
If you use Razor you can do:
#MvcHtmlString.Create(Html.Encode(strToEncode).Replace(Environment.NewLine, "<br />"))
in your view, or in your controller:
HttpServerUtility httpUtil = new HttpServerUtility();
MvcHtmlString encoded = httpUtil.HtmlEncode(strToEncode).Replace(Environment.NewLine, "<br />");
I have not tested the controller method, but it should work the same way.
Put your output inside <pre></pre> and/or <code></code> blocks. E.g:
<pre>#someValue</pre> / <code>#someValue</code>
Use the equivalent css on an existing div:
<div style="white-space:pre-wrap;">#someValue</div>
Depends whether you want the semantic markup or whether you want to fiddle with css. I think these are both neater than inserting <br/> tags.
/// <summary>
/// Returns html string with new lines as br tags
/// </summary>
public static MvcHtmlString ConvertNewLinesToBr<TModel>(this HtmlHelper<TModel> html, string text)
{
return new MvcHtmlString(html.Encode(text).Replace(Environment.NewLine, "<br />"));
}

Categories