Escape # character in razor view engine - asp.net-mvc-3

I am creating a sample ASP.NET MVC 3 site using Razor as view engine. The razor syntax starts with # character e.g. #RenderBody(). If I write #test on my cshtml page it gives me parse error
CS0103: The name 'test' does not exist in the current context
How do I escape '#' character?

## should do it.

Razor # escape char to symbols...
<img src="..." alt="Find me on twitter as #("#username")" />
or
<img src="..." alt="Find me on twitter as #("#")username" />

#Html.Raw("#") seems to me to be even more reliable than ##, since not in all cases ## will escape.
Therefore:
<meta name="twitter:site" content="#twitterSite">
would be:
<meta name="twitter:site" content="#Html.Raw("#")twitterSite">

use <text></text> or the easier way #:

Instead of HTML entity I prefer the use of #Html.Raw("#").

## is the escape character for # in Razor views as stated above.
Razor does however try to work out when an '#' is just an '#' and where it marks C# (or VB.Net) code. One of the main uses for this is to identify email addresses within a Razor view - it should not be necessary to escape the # character in an email address.

For the question about #RazorCodePart1 ## #RazorCodePart2, you need to the sequence:
#RazorCodePart1 #:## #RazorCodePart2
I know, it looks a bit odd, but it works and will get you the literal character '#' between the code blocks.

I just had the same problem. I declared a variable putting my text with the #.
#{
var twitterSite = "#MyTwitterSite";
}
...
<meta name="twitter:site" content="#twitterSite">

I know this question is old, but I tried all of the above and it didn't help me escape the character "#" in ASP.NET framework (MVC 5) inside a URL. Based on Terje Solem's answer though, the UTF-8 code %40 worked for me. this is the original URL I was trying to reach:
https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js
this is what worked for me in my code:
https://unpkg.com/%40google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js

this work for me
<meta name="author" content="Alan van Buuren #("#Alan_van_Buuren")">
Or yoy can use:
##Alan_van_Buuren
:D

You can use ## for this purpose.
Like var email = firstName + '\##' + domain;

I tried all the options above and none worked. This is what I did that worked :
#{
string str = #"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$";
}
<td>Email</td>
<td>
<input type="text" id="txtEmail" required name="email" pattern=#str />
</td>
I created a string varible and passed all the RegEx pattern code into it, then used the variable in the html, and Razor was cool with it.

just add a variable in CSHTML file
var myVariable = #"#";
and add it to your layout
<span class="my-class"><a href="#myVariale" target="_blank" >link text</a></span>

I couldn't get any of these to work inside my placeholder attribute, so I used xml special character.
<input type="text" placeholder="fex: firstname#lastname.com"/>
See more examples here.
https://www.dvteclipse.com/documentation/svlinter/How_to_use_special_characters_in_XML.3F.html

Actually # should be used with the Razor syntax Keywords or to the variable/model to bind a Value.
For Eg:
if test is assigned with value
i.e # { var test = "ABC" }
then you can get the value by settings as #test anywhere is cshtml page in html part.
otherwise, simple use as #Html.DisplayName("test")

I think in Razor view #Html.Raw() is the best solution for all version and always works for me. I have added an working example cdn URL to provide clear idea.
#Html.Raw("<script src=\"https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.6/dist/umd/popper.min.js\"></script>")

Related

Accessing Tag Helper output in Javascript

beginner question with Razor and tag helpers I'm afraid!
Using tag helpers in my razor html, I can e.g. write:
<div><date-picker id="datepicker" value="#DateTime.Now"></date-picker></div>
This will then generate the output
<input id="datepicker" class="datepicker" aria-atomic="true" aria-live="assertive" aria-expanded="false" role="combobox" name="datepicker" placeholder="Select date">
and so on. What I'd like to do is to append the output to other objects like dialog screens, which accept an html string to append.
e.g.
var customDesign = "<div id="something"><date-picker id="datepicker" value="#DateTime.Now"></date-picker></div>";
$(".myDialogfield").after(customDesign);
This doesn't work in Razor - I've tried various things like creating this as a HTML.Raw string first and injecting it as a variable etc - is there a way I can use the output from my tag helper within a script section?
Thanks for any hints!
You can't do it that way. TagHelpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. Here, it's just a JS string, and Razor will not mess with that.
Your best bet would likely to be some sort of JavaScript templating system, but generally speaking you could still get what you want manually via a different path. Instead of hardcoding a string of HTML, include the TagHelper in a script block of type text/html:
<script type="text/html" id="MyTemplate">
<date-picker id="datepicker" value="#DateTime.Now"></date-picker>
</script>
Then, in your JavaScript, you can select this script tag and get its content:
var customDesign = $('#MyTemplate').html();
$(".myDialogfield").after(customDesign);

Thymeleaf does not take localization in th:include

I trying to use Spring's localization bundle with Thymeleaf templates. It works well if it is used in normal templates, but fails if I apply th:include attribute at container tag.
I put the view code to Gist: https://gist.github.com/hron84/386bbf855148a601a3dc
The problematic localization is at line 4 and line 10. In the line 10 I see the correct expansion ("New machine") but in line 4, i just get "null" as the page title.
Could you please point me what do I wrong?
As Martin says, your th:include is replacing your title tag, you should do somthing like this:
<head>
<title th:text="#{page.title.machine.new}"> </title>
<dif th:include="widgets/_head :: head" th:remove="tag"></dif>
</head>
The th:remove="tag" will remove the dif tag.
The Thymeleaf website has some usefull documentation about the th:include and th:replace tags.
With th:include your are replacing the inner conten, ie the title tag, with the content fetched from the fragment. As you did not post the head fragment template i cannot give you more hints for that one. I suspect your title tag in the head fragment is doing something different for the title tag?

How to mix href within jstl code

When I use the below jstl code
<a href="http://mysite.com?id="<c:out value="${myid}"/>/><c:out value="${myid}"/></a>
the output is :
"1234"
The value 1234 corresponds to the variable value of myid but the url being generated is
"http://mysite.com?id=" so no value for myid is being generated as part of the href.
How can I amend the href so that entire href is displayed :
"http://mysite.com?id=1234"
instead of :
"http://mysite.com?id="
Ultimately, JSP/JSTL generates HTML. You're familiar with basic HTML, right?
Look closer at the generated HTML output by rightclick, View Source in browser. You'll see:
<a href="http://mysite.com?id="1234/>1234</a>
Is that valid HTML? No, you're closing the attribute value too soon with " at wrong place and you're closing the tag too soon with />. Look, the Stack Overflow HTML syntax highlighter also got confused. Instead, it should have been:
1234
Fix the HTML generator (i.e. the JSP/JSTL code) accordingly so that it generates the desired HTML:
<c:out value="${myid}"/>
Unrelated to the concrete problem, the <c:out> is only helpful in preventing XSS attack holes when redisplaying user-controlled input and actually the wrong tool to inline URL parameters. If you can guarantee that ${myid} is always a number (because it's a Long or Integer), you can even just leave it entirely out, making the code prettier to read:
${myid}
If the ${myid} is however not a guaranteed to be a number (because it's a String), then you should use <c:url> and <c:param> to properly URL-encode it:
<c:url value="http://mysite.com" var="myURL">
<c:param name="id" value="${myid}" />
</c:url>
<c:out value="${myid}" />
<c:url> tag is used to create an url. It is helpful in the case when cookies is turned off by the client, and you would be required to rewrite URLs that will be returned from a jsp page.
<c:param> tag may used as a subtag of to add the parameters in the returned URL. Using these parameters encodes the URL.
<c:url value="http://mysite.com" var="myURL">
<c:param name="id" value="${myid}" />
</c:url>
<a href="${myURL}" />${myURL}</a>
Read more from here.

ViewModel property being painted as literal text

I am a bit new to razor. So for the below, it's showing model.CarModelName as literal text instead of rendering the value for CarModelName
<p>Cars for for model.CarModelName </p>
Use the proper Razor Syntax:
<p>Cars for for #Model.CarModelName </p>
Quick Reference
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
Try #model.CarModelName. That denotes code that needs to be executed instead of just text.

How do HtmlAgilityPack extract text from html node whose class attribute appended dynamically

Dear friends,I want to extract text 平均3.6 星 from this code segment excerpted from amazon.cn.
<div class="content"><ul>
<li><b>用户评分:</b>
<span class="crAvgStars" style="white-space:no-wrap;">
<span class="asinReviewsSummary" ref="dp_db_cm_cr_acr_pop_" name="B004GUSIKO">
<a>
<span class="swSprite s_star_3_5 " title="平均3.6 星">
<span>平均3.6 星</span>
</span>
</a>
My question is span class tag value "s_star_3_5 " vary from different customer's rating level and appended dynamically. So I attempt to use doc.DocumentNode.SelectSingleNode(" //span[#class='swSprite']").InnerText or //span[#class='swSprite s_star_3_5 '], but the result is an error or not what my want !
Any suggestions?
First of all, I suggest you saving the value of doc.DocumentNode.OuterHtml to a local .html file and see if the code you're obtaining is that code. The thing is that sometimes you start parsing a website using HtmlAgilityPack, but the very first problem is that you're not getting the valid HTML correctly. Maybe you're getting a 404 error, or a redirection, etc.
I'm suggesting this because I tested //span[#class='swSprite s_star_3_5 '] and worked correctly.
That was the issue in the following questions:
Selecting nodes that have an attribute with spaces using HTMLAgilityPack
XPath Query Problem using HTML Agility Pack
If that doesn't help, post the HTML code and I'll help you ;)
This works for me:
HtmlDocument doc = new HtmlDocument();
doc.Load(myHtml);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//span[starts-with(#class, 'swSprite')]");
Console.WriteLine("Text=" + node.InnerText.Trim());
and outputs
平均3.6 星
Note I use the XPATH starts-with function.

Resources