Convert Razor String Variable to Javascript String Variable in MVC - javascript

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

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.

Passing a Django Object to Javascript

Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object.
However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong).
Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used #Mahdi Firouzjah's answer for this.
you could use ajax in templates and __ serialize in backend side.
then using javascript you're able to work with that object.

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

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

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

'parameterValue' in Javascript

Is 'parameterValue' a default parameter that is passed on an event in Javascript ?
Can anyone explain where this value comes from.
Load Ajax content
I found it used in the following article - http://www.easywayserver.com/blog/java-how-to-use-ajax-in-jsp/
In the context of that example, parameterValue is not important as it's discarded in the jsp file that is being called. In the javascript the parameters for the call are constructed as:
var url="loadJSP.jsp";
url=url+"?q="+str; /* url looks like loadJSP.jps?q=parameterValue */
In the file you'll see that q is being assigned as the parameter
String q =request.getParameter("q"); /* q = parameterValue */
But in the subsequent lines q is never used:
String str="This is JSP string loading from JSP page in ajax, loading time :";
java.util.Date dt=new java.util.Date();
out.print(str+dt);
"parameterValue" is any string value you want to pass through for the page's query string parameter called "q". The following line of code illustrates where it gets concatenated to the URL:
var url="loadJSP.jsp";
url=url+"?q="+str;
The JSP page on the server will then query the value of the parameter "q" and do something with it. In this instance, though, nothing is done with it. I'm assuming it's only there for illustration purposes.
It is just a plain string that you need to pass as a parameter to the loadContent() function in Javascript.You can replace 'parameterValue' by the actual value that you want to use.

Categories

Resources