set javascript variable value mvc c# [duplicate] - javascript

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 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

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

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

Regex to strip html tag with certain attribute

I have some invalidly-nested HTML like:
<form class="form1" method="get">
<div>
<input name="field1">
</form>
<form class="form2" method="get">
<input name="field1">
</form>
</div>
Yeah, it's a mess, don't ask. The invalid nesting is causing problems somewhere else. jQuery I think is expecting a closing </div>, and only finding it at the last one. It's then treating the second <form> tag as invalid, and also discarding the closing </form> immediately above it, and assuming everything between lines 1 and 9 are one form.
If I output these to the console:
$('.form1).html() - all of line 1 - 9
$('.form2).html() - undefined
So what I'm trying to do is treat the whole thing as a string, and use regex to strip out form2. I'm expecting a regex something like:
formText.replace(/(<form\b[^>]*>)[^<>]*(<\/form>)/gi, "");
but I'm not sure how to reference the specific form with class=form2.
There's also a problem with it being a multi-line string.
Update: added more detail, outlining why jQuery's remove() method isn't working. jQuery only thinks there's one form unfortunately.
Don't use regex to parse HTML. Since you're using jQuery, just use .remove():
$(function() {
$(".form2").remove();
});
JSFiddle
I ended up using:
formText = formText.replace(/(<form\b[^>]*form2+.*>[\s\S]+<\/form>)/gi, "");
The [\s\S] matches all characters including \n and \r to cover the newlines.
I could probably have made the part of the regex dealing with the class name more specific so I knew it was the class and not some other random form with a similar, but in practice it didn't matter (there was only one instance of the 2nd form, with a very specific class name).

Why I can't update the value of an input tag putting in it the € character using JQuery? I obtain € string instead €

I am pretty new in JavaScript\JQuery and I have the following problem:
Into a JSP page (but I think that this is not so important the type of page...it is a page that contain HTML) I have this input tag having id="saldoModale2":
<input id="saldoModale2" type="text" style="width: 25%" class="rightAlligned form-control" value='${progetto.impSal}' />
Then I have a JQuery script that, when the user click on a button, update the value of this input tag, in this way:
$("#saldoModale2").val('€');
So the previous line should only put the € character inside my input tag.
The problem is that instead see € in my input tag I obtain this strange value: €
The problem seems to be related to the € character because if I put the $ by:
$("#saldoModale2").val('$');
it perfectly works.
The strangest thing is that I have also tryied to perform this replacment into a JSFiddle: https://jsfiddle.net/AndreaNobili/4720ek9g/1/
and here seems works fine. So I am asking if it could depend by some charset\encoding properties of the file that implement my page, or something like this.
Why? What am I missing? What is wrong?
The issue is to do with the character encoding of the page. Try using the unicode value for € instead:
$("#saldoModale2").val('\u20ac');
Updated fiddle
Maybe you should add something like this to head section of your html?
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Showing text from resources.resx in JavaScript

This is example code in ASP.NET MVC 3 Razor:
#section header
{
<script type="text/javascript">
$(function() {
alert('#Resources.ExampleCompany');
});
</script>
}
<div>
<h1>#Resources.ExampleCompany</h1>
</div>
The code above this is just an example, but it also shows my problem with encoding. This variable #Resources.ExampleCompany is a file resources.resx with value ExampleCompany = "Twoja firma / Twój biznes"
In JavaScript, the alert shows the "Twoja firma / Twój biznes".
Why is character 'ó' '&#243'? What am I doing wrong?
In HTML tag, <h1>#Resources.ExampleCompany</h1> is displayed correctly.
UPDATE:
Mark Schultheiss wrote a good hint and my "ugly solution" is:
var companySample = "#Resources.ExampleCompany";
$('#temp').append(companySample);
alert($('#temp').text());
Now the character is ó and looks good, but this is still not answer to my issue.
According to HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine, the # syntax automatically HTML encodes and the solution is to use the Raw extension-method (e.g., #Html.Raw(Resources.ExampleCompany)) to decode the HTML. Try that and let us know if that works.
Some of this depends upon WHAT you do with the text.
For example, using the tags:
<div id='result'>empty</div>
<div id='other'>other</div>
And code (since you are using jQuery):
var whatitis="Twoja firma / Twój biznes";
var whatitisnow = unescape(whatitis);
alert(whatitis);
alert(whatitisnow);
$('#result').append(whatitis+" changed to:"+whatitisnow);
$('#other').text(whatitis+" changed to:"+whatitisnow);
In the browser, the "result" tag shows both correctly (as you desire) whereas the "other" shows it with the escaped character. And BOTH alerts show it with the escaped character.
See here for example: http://jsfiddle.net/MarkSchultheiss/uJtw3/.
I use following trick:
<script type="text/javascript">
$('<div/>').html("#Resources.ExampleCompany").text();
</script>
Maybe it will help.
UPDATE
I have tested this behavior of Razor more thoroughly and I've found that:
1.When the text is put as normal content of html then #Html.Raw method simply helps and writes char 'ó' without html encoding (not as: ó)
example:
<div> #Html.Raw("ó") </div>
example:
<script type="text/javascript">
var a = $('<div/>').html('#("ó")').text();// or var a = '#Html.Raw("ó")';
console.log(a); // it shows: ó
</script>
2.But if it is put inside html tags as attribute then Razor converts it to: ó and #Html.Raw doesn't help at all
example:
<meta name="description" content="#("ó")" />
Yo can fix it by putting the entire tag to Resource (as in that post) or to string (as in my example)
#("<meta name="description" content="ó" />")
So, sometimes somebody could have been little confused that the answers helps the others but not him.
I had similar issue, but in my case I was assigning a value from Resource to javascript variable. There was the same problem with letter ó encoding. Afterwards this variable was binded to a html object (precisely speaking by knockout binding). In my situation below code give a trick:
var label = '#Html.Raw(Resource.ResourceName)';

escape possible quotes in string passed to a js function in a onclick event

I have the following cycle in a jspx:
<c:forEach var="var" items="${dataFile.list.rows}">
<li>
<div>
<a href="#" onClick="myFunct('${var.url}','escape(${var.title}),'escape(${var.descr})');">
<img width="108" height="66" alt="" src="${var.img}" />
</a>
</div>
</li>
</c:forEach>
Where function myFunct does some stuff on its own. My problems arise when either ${var.title} or ${var.descr} contain quotes or double quotes. I can't know in advance whether there's going to be some or which.
I tried the above, I tried a little helper js section just before the element, but not knowing which kind of quotes I'm going to have I can't guess whether I need to put escape("${var.title}"); or escape('${var.title}');.
Any idea on how to solve this? Thanks.
You should do it in the server side, not in the client side. Doing it in the client side is too late anyway. Depending on the sole purpose of the value, whether it's going to be used as part of HTML and doesn't contain linebreaks, or as JS code, you can use either the JSTL-provided EL function fn:escapeXml()
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<a onclick="myFunct('${var.url}','${fn:escapeXml(var.title)}','${fn:escapeXml(var.descr)}');">
or create a custom EL function which uses Apache Commons Lang StringEscapeUtils#escapeJavaScript() under the covers.
<%#taglib prefix="my" uri="http://example.com/functions" %>
...
<a onclick="myFunct('${var.url}','${my:escapeJs(var.title)}','${my:escapeJs(var.descr)}');">
You can find a concrete example how to create an EL function at the bottom of this answer.
I guess that it's going to be used as part of HTML, so fn:escapeXml() could to be sufficient.
You don't need to create your own EL function but use apache-commons directly from your custom .tld:
<function>
<name>escapeJavaScript</name>
<function-class>org.apache.commons.lang.StringEscapeUtils</function-class>
<function-signature>java.lang.String escapeJavaScript(java.lang.String)</function-signature>
</function>
I suggest you encode on the server
http://www.roseindia.net/jsp/jsp-url-encoding.shtml
or store the stuff in a hidden element
<span id="url" style="display:none">${var.URL}</span>
<span id="title" style="display:none">${var.title}</span>
<span id="desc" style="display:none">${var.descr}</span>
and do onClick="return myFunct(['url','title','desc'])">...</a>
function myFunct(parms) {
var url = parms[0]?document.getElementById(parms[0]).innerHTML:"No url";
var title = parms[1]?document.getElementById(parms[1]).innerHTML:"No title";
var descr = parms[2]?document.getElementById(parms[2]).innerHTML:"No description";
return false;
}
You need to pass a valid JavaScript String literal to myFunct. escape is a JavaScriptfunction that expects a valid String as well. You thus need to transform you Java String into a valid JavaScript literal. Use apache commons-lang StringEscapeUtils.escapeECMAScript to escape it. You could make it an EL function, and thus use something like
onClick="myFunct('${myFn:escapeJs(var.url)}','${myFn:escapeJs(var.title)}, '${myFn:escapeJs(var.descr)}');"

How can I use a multiline value for an HTML tag attribute? (i.e. how do I escape newline?)

How do I include a newline in an HTML tag attribute?
For example:
<a href="somepage.html" onclick="javascript: foo('This is a multiline string.
This is the part after the newline.')">some link</a>
Edit: Sorry, bad example, what if the tag happened to not be in javascript, say:
<sometag someattr="This is a multiline string.
This is the part after the newline." />
Edit 2: Turns out the newline in the string wasn't my problem, it was the javascript function I was calling. FWIW, "
" can be used for newline in an HTML attribute.
From what I remember about the HTML standard, character entities work in attributes, so this might work:
<sometag someattr="This is a multiline string.
This is the part after the newline." />
I'm not sure if the "newline" you want ought to be
(\n) or
(\r\n), and I'm not sure if browsers will interpret it the way you want.
Why do you need it? What specific problem are you trying to solve by adding a newline in an HTML tag attribute?
To include a multiline value, just continue the text of the html attribute on the next line in your editor e.g.
<input type="submit" value="hallo
hallo">
will put the second hallo under the first
As a general rule newlines in attributes are preserved so your second example would work fine. Did you try it? Can you give a specific example where you are having problems with it?
As test take a look at this:-
<a href="somepage3.html" onclick="javascript: alert(this.getAttribute('thing'))" thing="This is a multiline string.
This is the part after the newline.">some link</a>
The alert include the newline in the attribute.
<a href="somepage.html" onclick="javascript: foo('This is a multiline string. \
This is the part after the newline.')">some link</a>
Javascript needs a backslash at the end of the new line in a string.
i'm not certain, but you can try \r or \n
javascript: foo('This is a multiline string.\rThis is the part after the newline.')
or
javascript: foo('This is a multiline string.\nThis is the part after the newline.')
Usually, line breaks in HTML source code display what you intended in the result.
(Depends on the editor of course)
Since it's in Javascript, you would use "\n" if inside double-quotes (not positive about single-quotes, I've been in PHP a lot lately.
Honestly, it's worth mentioning that you should use Events and a delegator instead of placing a javascript event directly on the element.

Categories

Resources