ASP.NET MVC / JavaScript - Decode Encoded HTML String from C# amper - javascript

I am attempting to access a static piece of HTML from JavaScript. Here is what I am doing:
In _Header.cshtml:
#{
string HTMLContent = #Server.HtmlDecode("<div>Hello World</div>");
}
<script type="text/javascript">
var StaticHTML = #HTMLContent;
</script>
However, I am getting the following error:
Uncaught SyntaxError: Unexpected token &
When I step through it does appear that the HTMLContent variable is being printed in JavaScript as if it were Unencoded.
What am I missing here?

When razor executes the code in your view, # will encode the value of your C# expression. So you want to avoid doing that. You may use Html.Raw method which does not do any html encoding.
Since you are assigning the value to the js variable, you should wrap it in quotes(single or double).
This should work.
var StaticHTML = "#Html.Raw(HTMLContent)";
console.log(StaticHtml);

Related

JavaScript escape sequence cannot read a variable value while concatenation?

I am working in a Laravel application. I want to concatenate a variable with a string using escape sequence (` `) in JS. A normal concatenation of strings and variable work fine using escape sequence. But it does not work and throws error when I concatenate PHP route string with a parameter. You will have an idea when you see the below code.
<script>
function changeStatus(value, applicationId){
var url = `"{{route('application.toggle.approval',['id'=> ${applicationId} ])}}"`;
console.log(url);
}
</script>
I am not being able to pass any kind of variable there. It is giving me error like below:
(2/2) ErrorException
Use of undefined constant applicationId - assumed 'applicationId' (View: C:\wamp64\www\oibn\app\Modules\Application\Views\applicationShowProtected.blade.php)
How do I pass the variable there? I can console.log the parameters passed in the function. But that value is not getting passed in concatenation. It gives error only. Please help.

Why declaring a simple JSON object into a JavaScript script executed into Rhino is not working?

I am not so into JavaScript. I am using JavaScript to develop a litle script working on a JSON document. This JavaScript script is not executed into the browser but ino another product that allow to use JavaScript to script some tasks (the prodcut is WSO2 ESB but it is not important at this time).
This product (WSO2 ESB) uses Rhino as JavaScript engine, used to implement JavaScript scripts into Java application.
I have some problem trying to create a simple JSON object in this kind of environment.
I have done something like this (into my WSO2 ESB code):
<script language="js">
<![CDATA[
var response = JSON.parse(`
{
"forecast": []
}
`);
]]>
</script>
Using the same code into a classic JavaScript file performed into the broswer it works fine but it seems that it can't work using Rhino. I obtain error relating an illegal character (I also tryied to replace the ` and ` with " and " and with ' and ' but I still obtain error).
Something like this in the Java Stacktrace:
Caused by: javax.script.ScriptException: org.mozilla.javascript.EvaluatorException: illegal character (<Unknown Source>#9)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:341)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:323)
at org.apache.synapse.mediators.bsf.ScriptMediator.initInlineScript(ScriptMediator.java:399)
... 32 more
What could be the problem with Rhino? I think that the problem could be related to the `` character that maybe have to be escaped in some way. Some idea?
Or another something more pure JavaScript workaround solution could be: is it possible declare a JSON object like this:
{
"forecast": []
}
in a different way? I mean in a programmatically way without explicitly declare it.
This works in modern browsers that support ES6 with template literals:
var response = JSON.parse(`{"forecast": []}`);
Why, because JavaScript solves the back ticks first as a template and fills them with the content of the variables before the JSON string is parsed:
var test = "Cloudy";
var string = `{\"forecast": ["${test}"]}`;
var response = JSON.parse(string);
console.log(response);
But maybe your Rhino build has no ES6 support, so that won't work. Also the multiline is causing problems:
var response = JSON.parse(''+
'{'+
' "forecast": []'+
'}'
);
console.log(response);

Convert Razor String Variable to Javascript String Variable in MVC

I am trying to pass my string variable (even boolean) on my cshtml view to my javascript section. I can successfully pass the value from razor section to javascript if its integer. But what I want to accomplish is to pass the string value. Here is my sample code from my .cshtml:
string strAnnouncement = "My announcement";
int intCounterValue = 1200;
To receive the value on Javascript, here is my code:
//Cannot get the value, always error on Developer Tool console
var SessAnnouncement = #strAnnouncement;
//Can get the value successfully
var SessInitTimer = #intCounterValue;
As you can see, I can get the value via javascript on SessInitTimer which is 1200. But on SessAnnouncement, I get a Uncaught ReferenceError: My announcement is not defined.
How can I get the strAnnouncement value on my razor section and pass it on script section?
They are treated as variable and since you have not defined them you get the said error.
You need to wrap in quotes to be treated as string.
var SessAnnouncement = "#strAnnouncement";
A better approach would be to use JSON.Encode() method
var SessAnnouncement = #Html.Raw(Json.Encode(strAnnouncement));

Javascript var with a newline using MVC Model property

I have to set a Javascript variable to equal a property in my MVC model.
I am doing this to detect if any changes were made to a textbox, this is setting the "original" value.
My Javascript code looks like this:
var initVal = '#Model.ReferralHistoryDetail[1].ReferralComments';
I am getting an error, which I assume is due to this containing carriage returns in the comments.
Uncaught SyntaxError: Unexpected token ILLEGAL
The HTML being rendered in this case is putting the closing quote on a newline, and that is the error being shown in the developer console.
For example, the rendered HTML is:
var initVal = 'blah blah blah
';
What is the proper way to handle this?
You want to use the JavaScriptStringEncode command to encode the string in a javascript compatible way.
var initVal = '#HttpUtility.JavaScriptStringEncode(Model.ReferralHistoryDetail[1].ReferralComments)';
If you replace \n character by \,
you will have a valid syntax for multiple lines string.
So that should work
var initVal = '#Model.ReferralHistoryDetail[1].ReferralComments.Replace("\n","\\")';
I found other ways to allow multiple line string in javascript,
in this answer.
You need to create an extension method that replaces the new line character with tags.
Or use the method HtmlEncode
like this:
var initVal = #Html.Raw(HttpUtility.HtmlEncode(#Model.ReferralHistoryDetail[1].ReferralComments).Replace("\n", "<br />"))
You cannot access Model properties from JavaScript like that, JavaScript cannot do anything with your model.
Create a variable up the page
#{ var value = #Model.ReferralHistoryDetail[1].ReferralComments;
Then access value in javascript, though not sure why you don't just render directly on page why do you need javascript unless I am missing something

Can't pass double quotes JSON to Javascript from Android Java

Scenario:
TLDR; Why can I not pass ("") from Android to JavaScript, only ('') works?
I'm sending a JSON object from Android to JavaScript through:
mWebView.loadUrl("javascript:foo(\"" + bar + "\")");
To my knowledge this calls the javascript function foo() passing it the value of bar.
The bar variable is a JSON object for example:
bar = "{'id':'"+barID+"','title':'"+barTitle+"'}";
Now on the javascript side the function foo() does the following:
function foo(json){
var completeJsonObject;
json = json.replace(/'/g, '"');
completeJsonObject = JSON.parse(json);
}
This works perfectly as it replaces the (') with ("") and then the json can be parsed.
However to avoid having to replace I could just format the json on the java side with ("") instead like bellow right?
bar = "{\"id\":\""+barID+"\",\"title\":\""+barTitle+"\"}";
Well no, as soon as I do that the JavaScript gives me an unexpected token error.
Is there a better way to fix this than with my solution?

Categories

Resources