# statement in razor templates shows HTML symbols instead of quotes - asp.net-mvc

I've noted that # statement in Razor templates converts quotes in strings into HTML symbols.
How can I show correct HTML attribute then? Sample code:
<body#(ViewBag.Highlight == true ? " onload=\"prettyPrint()\"" : "")>
result:
<body onload="prettyPrint()">
That's completely incorrect. How can i achieve normal:
<body onload="prettyPrint()">
in my case?
I've tried HtmlString object from this answer. But it's impossible to convert HtmlString to string even with explicit type cast.

You will need to use Html.Raw(). Try it this way:
#Html.Raw(String.Format("<body{0}>", ViewBag.Highlight == true ? " onload=\"prettyPrint()\"" : ""))
As the documentation says:
Returns markup that is not HTML encoded.

Related

How to render HTML predefined tag in Razor view?

I want to render the HTML predefined tag (between h2 to h6) based on what is set in my model. Below is the snippet. I am facing issue in my closing tag. closing tag is not processed and it is considered as text and it is truncated in the page view source.
string subArticleLevel = "h2";
if(subarticle.SubTitleLevel!=null)
{
subArticleLevel = subarticle.SubTitleLevel;
}
<#subArticleLevel>#subarticle.SubTitle</#subArticleLevel>
You can use Html.Raw method with explicit code block notation.
#Html.Raw("<")#(subArticleLevel)#Html.Raw(">")#(subarticle.SubTitle)
#Html.Raw("</")#(subArticleLevel)#Html.Raw(">")
Or
Simply use #: prefix to denote it is a start of an html block, if you are already in a code block. The below should work fine.
#{
string subArticleLevel = "h2";
string subarticleSubTitle = "test";
#:<#subArticleLevel>#subarticleSubTitle</#subArticleLevel>
}
I'm not sure what version of MVC you are on but if you have c# 6 you might just use c# string interpolation.
#($"<{subArticleLevel}>{subarticle.SubTitle}</{subArticleLevel}>")
I haven't tried it but if you are getting html encoding you could try.
#Html.Raw($"<{subArticleLevel}>{subarticle.SubTitle}</{subArticleLevel}>")
If you don't have c# 6 available you can try .
#Html.Raw(string.Format("<{0}>{1}</{0}>", subArticleLevel, subarticle.SubTitle))

#HttpContext.Current.User.Identity.Name not showing backslash

Super Simple. Only issues I find are people getting null. Which I obvi fixed. But where is the backslash???!!
params.me = '#HttpContext.Current.User.Identity.Name';
This returns
"domainUserName" <- Browser
"domain\\UserName" <- Debugging
What I expect is
"domain\UserName" <- Browser
Any ideas?
Based on your comments you are using the following code to show the user name:
alert('#HttpContext.Current.User.Identity.Name');
#HttpContext.Current.User.Identity.Nameis a string that can contain "\" backslash character. This character is considered as a escape character in javascript as it is in C# as well.
You need to escape the "\" character in the string before passing it to Javascript like that:
alert('#HttpContext.Current.User.Identity.Name.Replace("\\", "\\\\")')

How to deal with dynamic urls with special characters like single quote?

I am generating dynamic an "a href" html tag on my asp page. Also the url is dynamic. Sometimes there are special characters inside the url and the hyperlink is not working. For example when there is an single quote:
http://myCompany.com/'s-hertog.aspx
How can I fix this that the dynamic url always will work?
I already try this, but is not working:
string hyperLinkHtml = string.Format("<span class=\"bw-NewsQueryWebpart-BodyItemTitle\"><a href='{0}' >{1}</a>", HttpUtility.UrlEncode(newsItem.Url), newsItem.Title);
I found the solution by my self. I changed the single quotes to double quotes in the string.format:
string hyperLinkHtml = string.Format("<span class=\"bw-NewsQueryWebpart-BodyItemTitle\"><a href=\"{0}\" >{1}</a>", HttpUtility.UrlEncode(newsItem.Url), newsItem.Title);

Why does to_json escape unicode automatically in Rails 4?

Rails 3:
{"a" => "<br/>"}.to_json
=> "{\"a\":\"<br/>\"}"
Rails 4:
{"a" => "<br/>"}.to_json
=> "{\"a\":\"\\u003Cbr/\\u003E\"}"
WHY???
It appears to be causing the error
Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8
When my Rails 3 app tries to parse JSON generated by my rails 4 app.
WHY???
To defend against a common weakness in web applications. If you say in an HTML page eg:
<script type="text/javascript">
var something = <%= #something.to_json.html_safe %>;
</script>
then you might think you're fine because you've JSON-escaped the data you're injecting into JavaScript. But actually you're not safe: aside from JSON syntax you also have surrounding HTML syntax, and in an HTML script block </ is in-band signalling. Practically, if #something contains the string </script> you've got a cross-site scripting vulnerability as this comes out:
<script type="text/javascript">
var something = {"attack": "abc</script><script>alert('XSS');//"};
</script>
The first script block ends halfway through the string (leaving an unclosed string literal syntax error) and the second <script> is treated as a new script block and the potentially-user-submitted content within it executed.
Escaping the < character to \u003C is not required by JSON but it is a perfectly valid alternative and it automatically avoids this class of problems. If a JSON parser rejects it, that is a severe bug in the reader.
What is the code that is producing that error? I'm not convinced the error is anything to do with the <-escaping, as it is talking about byte 0xC3 rather than 0x3C. That could be indicative of a string with UTF-8 encoded content not having been marked as UTF-8... maybe you need a force_encoding("UTF-8") on the input?
You can retain the original string with JSON::dump:
JSON::dump "a" => "<br/>"
=> "{\"a\":\"<br/>\"}"
JSON::dump "a" => "x&y"
=> {\"a\":\"x&y\"}" # instead of x\u0026y
Use it with care for the reasons bobince mentions and particularly avoid it with any user-generated input (or at least make sure that's sanitized).
Here's an example I encountered where it's a legitimate use. Generating a JavaScript hash argument in a helper function:
# application_helper.rb
def widget_js(post)
options = {
color: ColorCalculator(post.color).to_rgb_hex,
...
}
"third_party_widget(#{JSON::dump options});"
end
I encountered this issue too and as others have mentioned, it's caused by using the ActiveSupport to_json method. To resolve, use the JSON gem directly with JSON.generate(data) where data is an Array or Hash. See https://github.com/flori/json for all JSON gem documentation.
Was having a similar problem with Rails 7 sending "<" in JSON output like:
..., "legend":[{"text":"<96.8%","color":"#FFAFFF"},{"text":"96.8% to 98.8%","color":"#E37DE3"},{"text":"98.8% to 100%","color":"#BA50BA"}], ...
from something like:
{entry: dataset.entry, legend: dataset.legend, ...
The "<" sign was showing up "legend":[{"text":"\u003c96.8%", ...
In my case `JSON.generate({entry: ...})` fixed the issue

Looking for guide line about Razor syntax in asp.net mvc

i am learning asp.net mvc just going through online tutorial
1) just see <span>#model.Message</span> and #Html.Raw(model.Message)
suppose if "Hello Word" is stored in Message then "Hello Word" should display if i write statement like
<span>#model.Message</span> but i just could not understand what is the special purpose about #Html.Raw(model.Message).
what #Html.Raw() will render ?
please discuss with few more example to understand the difference well.
2) just see the below two snippet
#if (foo) {
<text>Plain Text</text>
}
#if (foo) {
#:Plain Text is #bar
}
in which version of html the tag called was introduce. is it equivalent to or what ? what is the purpose of
this tag ?
just tell me about this #:Plain Text is #bar
what is the special meaning of #: ?
if our intention is to mixing text with expression then can't we write like Plain Text is #bar
3) <span>ISBN#(isbnNumber)</span>
what it will print ? if 2000 is stored in isbnNumber variable then it may print <span>ISBN2000</span>. am i right ?
so tell me what is the special meaning of #(variable-name) why bracket along with # symbol ?
4) just see
<span>In Razor, you use the
##foo to display the value
of foo</span>
if foo has value called god then what this ##foo will print ?
5 ) see this and guide me about few more syntax given below point wise
a) #(MyClass.MyMethod<AType>())
b)
#{
Func<dynamic, object> b =
#<strong>#item</strong>;
}
#b("Bold this")
c) <div class="#className foo bar"></div>
6) see this
#functions
{
string SayWithFunction(string message)
{
return message;
}
}
#helper SayWithHelper(string message)
{
Text: #message
}
#SayWithFunction("Hello, world!")
#SayWithHelper("Hello, world!")
what they are trying to declare ? function ?
what kind of syntax it is ?
it seems that two function has been declare in two different way ? please explain this points with more sample. thanks
Few More question
7)
#{
Func<dynamic, object> b = #<strong>#item</strong>;
}
<span>This sentence is #b("In Bold").</span>
what the meaning of above line ? is it anonymous delegate?
when some one will call #b("In Bold") then what will happen ?
8)
#{
var items = new[] { "one", "two", "three" };
}
<ul>
#items.List(#<li>#item</li>)
</ul>
tell me something about List() function and from where the item variable come ?
9)
#{
var comics = new[] {
new ComicBook {Title = "Groo", Publisher = "Dark Horse Comics"},
new ComicBook {Title = "Spiderman", Publisher = "Marvel"}
};
}
<table>
#comics.List(
#<tr>
<td>#item.Title</td>
<td>#item.Publisher</td>
</tr>)
</table>
please explain briefly the above code. thanks
1) Any kind of #Variable output makes MVC automatically encode the value. That is to say if foo = "Joe & Dave", then #foo becomes Joe & Dave automatically. To escape this behavior you have #Html.Raw.
2) <text></text> is there to help you when the parser is having trouble. You have to keep in mind Razor goes in and out of HTML/Code using the semantics of the languages. that is to say, it knows it's in HTML using the XML parser, and when it's in C#/VB by its syntax (like braces or Then..End respectively). When you want to stray from this format, you can use <text>. e.g.
<ul>
<li>
#foreach (var item in items) {
#item.Description
<text></li><li></text>
}
</li>
</ul>
Here you're messing with the parser because it no longer conforms to "standard" HTML blocks. The </li> would through razor for a loop, but because it's wrapped in <text></text> it has a more definitive way of knowing where code ends and HTML begins.
3) Yes, the parenthesis are there to help give the parser an explicit definition of what should be executed. Razor makes its best attempt to understand what you're trying to output, but sometimes it's off. The parenthesis solve this. e.g.
#Foo.bar
If you only had #Foo defined as a string, Razor would inevitably try to look for a bar property because it follows C#'s naming convention (this would be a very valid notation in C#, but not our intent). So, to avoid it from continuing on we can use parenthesis:
#(Foo).bar
A notable exception to this is when there is a single trailing period. e.g.
Hello, #name.
The Razor parser realizes nothing valid (in terms of the language) follows, so it just outputs name and a period thereafter.
4) ## is the escape method for razor when you need to actually print #. So, in your example, you'd see #foo on the page in plain text. This is useful when outputting email addresses directly on the page, e.g.
bchristie##contoso.com
Now razor won't look for a contoso.com variable.
5) You're seeing various shortcuts and usages of how you bounce between valid C# code and HTML. Remember that you can go between, and the HTML you're seeing is really just a compiled IHtmlString that is finally output to the buffer.
1.
By default, Razor automatically html-encodes your output values (<div> becomes <div>). #Html.Raw should be used when you explicitly want to output the value as-is without any encoding (very common for outputting JSON strings in the middle of a <script>).
2.
The purpose of <text> and #: is to escape the regular Razor syntax flow and output literal text values. for example:
// i just want to print "Haz It" if some condition is true
#if (Model.HasSomething) { Haz It } // syntax error
#if (Model.HasSomething) { <text>Haz It</text> } // just fine
As of #:, it begins a text literal until the next line-feed (enter), so:
#if (Model.HasSomething) { #:Haz It } // syntax error, no closing '}' encountered
// just fine
#if (Model.HasSomething)
{
#:Haz It
}
3.
By default, if your # is inside a quote/double-quotes (<tr id="row#item.Id"), Razor interprets it as a literal and will not try to parse it as expression (for obvious reasons), but sometimes you do want it to, then you simply write <tr id="row#(item.Id").
4.
The purpose of ## is simply to escape '#'. when you want to output '#' and don't want Razor to interpret is as an expression. then in your case ##foo would print '#foo'.
5.
a. #(MyClass.MyMethod<AType>()) would simply output the return value of the method (using ToString() if necessary).
b. Yes, Razor does let you define some kind of inline functions, but usually you better use Html Helpers / Functions / DisplayTemplates (as follows).
c. See above.
6.
As of Razor Helpers, see http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Resources