Showing text from resources.resx in JavaScript - 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)';

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

set javascript variable value mvc c# [duplicate]

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

Convert HTML text area value to jqmath formula

I am new to jqmath; I have contained a textarea field in my HTML:
<textarea cols="30" rows="2" id="mathSrc1"></textarea>
I will set mathematical formula in the text area so that it will be displayed in <div> tag:
<div id="mathTgt1"></div>
This code is available in http://mathscribe.com/author/jqmath.html. But I don't know how to use it. Please help me.
Thank you.
i got solution
<input type="textarea" name="formula" id="test_formula" onkeyup="paste_formula()" />
<span id="formula_print"></span>
script code
function paste_formula() {
var val = document.getElementById("test_formula").value;
val = "$$" + val + "$$";
var di = document.getElementById("formula_print");
di.innerHTML = val;
M.parseMath(di);
}
I like Nathan's question - what exactly are you trying to do? The normal case is to have some math in your static web page, which you just surround with $s and it gets parsed and formatted at load time. If you want to create mathematical expressions dynamically (after load time), see Jqmath - apply after page load. You can also look at the jqmath source to see how http://mathscribe.com/author/jqmath.html does it. All these methods end up calling the same functions to do the actual work (parsing and formatting).

Make Vim correctly highlight script type="text/html"

How can I get Vim to correctly syntax-highlight in a situation such as this (used, e.g. with Knockout templates):
<script type="text/html" id="my-template">
<!-- This should be rendered as HTML -->
<div>Some template</div>
</script>
<script>
//This should be rendered as Javascript
var x = function() { return 3; }
</script>
The solution given here involves editing Vim's internal syntax file, which seems wrong, and it specifically looks for "text/javascript" which is no longer needed in <script> tags.
I assume the solution is some sort of syntax plugin I can keep in my .vim directory but am not familiar enough with Vim's syntax internals to figure it out.
(Note that this question and answer don't apply as I'm not using Ruby on Rails.)
Maybe this will help you: https://coderwall.com/p/vgk5-q/make-vim-play-nice-with-html-templates-inside-script-tags.
In case the link above is broken one day - put the following code into ~/.vim/after/syntax/html.vim:
unlet b:current_syntax
syn include #HTML $VIMRUNTIME/syntax/html.vim
syn region htmlTemplate start=+<script [^>]*type *=[^>]*text/template[^>]*>+
\ end=+</script>+me=s-1 keepend
\ contains=#HTML,htmlScriptTag,#htmlPreproc
Somebody should write a plugin for that! ;)
First copy the vim's internal html syntax file to $HOME/.vim/syntax/html.vim so that you only change the behaviour for yourself not globally.
Then find the line starting syn region javaScript and replace it with two lines
syn region script_notype start=+<script>+ keepend end=+</script>+me=s-1 contains=#htmlJavaScript,htmlCssStyleComment,htmlScriptTag,#htmlPreproc
syn region script_jstype start=+<script[^>]*type="text/javascript"[^>]*>+ keepend end=+</script>+me=s-1 contains=#htmlJavaScript,htmlCssStyleComment,htmlScriptTag,#htmlPreproc
The first line is for plain <script> tab, the second for <script type="text/javascript">.
However, this won't cover a situation with <script> tag without type attribute having other attributes. This case should get javascript syntax but won't. I guess this is a minor problem.

EpicEditor text showing as instead of space

Not sure if this is an actual problem per se but I'm using Epic Editor to input and save markdown in my GAE application (webpy with mako as the templating engine).
I've got a hidden input element in the form which gets populated by the EpicEditor's content when I submit the form but all the white spaces are replaced by . Is this an intended feature? If I check the same code on the EpicEditor site, it clearly returns spaces instead of so what's different about mine?
<form>
<!-- form elements -->
<input id="content" name="content" type="hidden" value></input>
<div id="epiceditor"></div>
<button type="submit" name="submit" id="submit">submit</button>
</form>
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML; //all the spaces are returned as and breaks are <br>
$('input#content').html(content);
});
</script>
NOTE: I want to save my content as markdown in a TextProperty field my data store and generate the html tags when I retrieve it using marked.js
I'm the creator of EpicEditor. You shouldn't be getting the innerHTML. EpicEditor does nothing to the innerHTML as you write. The text and code you are seeing will be different between all the browsers and it's how contenteditable fields work. For example, some browsers insert UTF-8 characters for spaces some &nbsp.
EpicEditor gives you methods to normalize the text tho. You shouldn't ever be trying to parse the text manually.
$('button#submit').click(function(){
var content = editor.exportFile();
$('input#content').html(content);
});
More details on exportFile: http://epiceditor.com/#exportfilefilenametype
P.S. You don't need to do input#content. Thats the same as just #content :)
You can do this if you dont find out why:
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML;
content = content.replace(" ", " ");
$('input#content').html(content);
});
</script>
[EDIT: solved]
I shouldn't be using innerHTML, but innerText instead.
I figured out that Epic Editor uses on all spaces proceeding the first one. This is a feature, presumably.
However that wasn't the problem. ALL the spaces were being converted to , eventually, I realised it occurs when Epic Editor loads the autosaved content from localStorage.
I'm now loading content from my backend every time instead of autosaving. Not optimal, but solves it.

Categories

Resources