How to transfer mvc view javascript code to separate js file - javascript

I am using Knockoutjs in my asp.net MVC-5 application. I have the following javascript in view:
<script type="text/javascript">
var model = "#Html.Raw(Json.Encode(Model))";
$.get("#Url.Action("_CityPartial")" ...)
//any much more code using similar Html helpers + pure javacsript code.
</script>
Now i want to know, is there any way to transfer this javascript code in a separate js file (keeping Html helpers as it is).
I want to transfer javascript code to separate file because i dont want any user to check my javascript code (using chrome inspect element or any other way).
If the transfer is not possible than please let me know if there is a any way to minifiy the javascript in view itself ??

You could create an external .js file with your code in and pass your serialized json object to it like this:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
DoThis(model);
</script>
This has the benefits of keeping the main body of javascript in a separate file.
Any other razor variables can be passed across to the methods defined in the javascript in the same manor as the model has been above.
However as Stanyer mentions this is still javascript and it will run on the client.

You can load it via an external JavaScript file, but unfortunately as JavaScript is a client-side scripting language regardless of whether its loaded inline or externally, the client can still view the code which is being executed on their browser.
You mention minifying - again this can still be interpreted by a client if they really wanted to see your code, but there are many tools online which can minify your JavaScript for you.
Examples:
http://jscompress.com/
http://www.jsmini.com/

No you cant keep the #Html helpers in external javascript file. They are all server side syntax and will be rendered in your HTML page inline.
What maximum you can do is, assign it in a var variable in your page and refer it inside a external page.

Related

Thymeleaf syntax is not working in java script file

I am using spring boot to provide data to thymeleaf.
var list = [(${listStudents})];
listStudents is a list of students with the help of which I populate data in HTML which is working fine but fetching the same list in java script using thymeleaf shows error in the above line as:
, expected.
I have added th:inline="javascript" attribute to script tag in HTML file as:
<script th:inline="javascript" src="home_script.js"></script>
Trying to solve this since yesterday.
Thanks in advance!
The , expected error is the standard JavaScript syntax error for var list = [(${listStudents})];. To handle this, Thymeleaf supports placing its inline expressions inside JavaScript comments:
var list = /*[[${listStudents}]]*/ [];
Because the Thymeleaf expression is in a JS comment, note how we have to provide a default (visible) JS value, to keep JavaScript from raising a different syntax error. I used [] because you have a list. You could have used '', or null or whatever is most suitable. Assuming your Thymeleaf is rendered correctly, this extra syntax will be ignored.
See JavaScript natural templates for details.
However, I do not think this will completely resolve your problem, unless you have already configured a JavaScript template resolver in your application.
You are using this:
<script th:inline="javascript" src="home_script.js"></script>
First of all, the th:inline="javascript" portion has no effect, because your JavaScript code is in an external file: home_script.js (i.e. it is not embedded in your HTML file).
If you want Thymeleaf to process the Thymeleaf expressions in that separate JS file, you have to tell Thymeleaf to explicitly process external JavaScript files (just like it processes HTML files).
You probably only have a HTML resolver - and your JS code is not embedded in your HTML file - it is in its own separate JS file. See this demo application which shows how to set up what I think you may need.
Alternatively you can simply embed your JS directly into the <body> of your HTML file, and don't use an external JS file:
<body>
<script th:inline="javascript">
var list = /*[[${listStudents}]]*/ [];
</script>
</body>
If you still need to use an external JS file, you can assign all your Thymeleaf-generated variables inside your HTML file (like the example above) and then pass these variables as function parameters into the various JavaScript functions in your JS file.
Using this approach means your JS file does not need to contain any Thymeleaf expressions - it just receives the rendered values from the JS fragment in your HTML file.
You should use [[${listStudents})]] (so 2 square brackets, not using round brackets)

How to use resx file in javascript file. .net core 3.1 mvc

I'am developing multi language web site with .net core mvc.
I used Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer.
This code is work fine in .cshtml for me
#inject Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer<ExampleProject.WEB.Controllers.HomeController> localizer
#localizer["NotificationManage"]
Also works between <script> tags in _Layout page
alert('#localizer["NotificationManage"]');
But don't working in js file.
How to use Resx file in javascript file.?
What another best to way make multi language to javascript?
alert('#localizer["NotificationManage"]');
Not working for me.
Alert Result is:#localizer["NotificationManage"];
One possible solution is to define your translations as a global variable on the window outside your script
<script>
var translations = {
notification: '#localizer["NotificationManage"]'
}
</script>
<script type="text/javascript" src="pathtoscript.js"></script>
then inside your script you go
alert(window.translations.notification);
If any better solution is given here I'm happy to hear, because we use it this way in production
Another approach we could consider is to create a custom tag helper to convert the resource file contents to a global javascript object and then this variable object can be directly accessed in the external js files
It is mentioned in detail in this blog javascript localization worth a read.

How many ways are there to maintain handlebars template in client side

In my application we are templating handlebars from client side(we are not templating from server side).So till now we used maintaining all templated inside of the html file using script tag like in the following way.
<script id="selectdropdownTpl_mobile" type="text/x-handlebars-template">
<option value="{{optValue}}" label="{{name}}">{{name}}</option>
</script>
Whenever I want template, I am just compiling and appending compiled result to dom just like following way
var alertCompilation= Handlebars.compile(document.getElementById("selectdropdownTpl_mobile").innerHTML)
alertCompilation({"optValue":"test","name":"firstApp});
Working fine,but what we are thinking to separate all handlebar templates into another file.so it's easy to maintain html file.
Regarding this,I thinking to move all the templates into .js file inside of the file just creating global variable,it is object in the following way.
//fileName test.js
var templates={
"selectdropdownTpl_mobile":"template code"
}
whenever I want, I can access template code like in the following way.
var alertCompilation= Handlebars.compile(templates["selectdropdownTpl_mobile"]);
alertCompilation({"optValue":"test","name":"firstApp});
This way also working fine,What I want to know is this good way or not.If it is not good way How shell do this.
I heard about .hbs file, basically it contains pre-compiler template.It's usefull If I template from server side but in my case templating happening in client side itself.
can anyone suggest me,which way is better.

How to read model attribute from js outside jsp

If my javascript/jquery code is written inside a jsp-file, I can refer to Spring's modelAttribute value with "${varName}".
However I would like to move the javascript code into it's own file to keep the jsp-file more readable. When I do that, it won't however be able to find that modelAttribute anymore. How should I solve this problem?
How can I point to model attribute from a .js -file?
Thanks in advance!
Alright, I've experimented on my end to try to find and answer for this question.
Actually, it seems there's no direct solution, and here's why:
When you are moving your Javascript code to a separate file, this means that the browser will launch a separate request to fetch that file. As such, data that you store in your request scope (a.k.a. ${varName}) is not part of the request that fetches the .js file; it's only part of the request that fetches your .jsp file instead. As such, the ${varName} value will not be available in your Javascript file.
Another reason on top of the above: .js files are not processed as server-side code by the web engine (most likely Tomcat in this case), so the ${varName} text is outright ignored. For fun, I tried to do a hack: I renamed my script file from .js to .jsp, and used this within my .jsp page:
<script type="text/javascript" src="js/actually_javascript.jsp"></script>
It fooled the web server to process the file server-side, but this still didn't work, because of reason #1 stated above. It could work if you stored the value in the session instead, but at the end of the day, it would be kind of an ugly hack and you'd lose out on the code highlighting and completion features of your IDE, which would be fooled into thinking you're editing an actual .jsp file. Not recommended.
To conclude, I think the only way to access {$varName} inside your JavaScript is either:
Having the Javascript being a part of your .jsp file, within <script> tags
Having your Javascript in its own .js file, but still having a <script> tag in your .jsp page which initializes the module you programmed in the .js file and passes the values from the request, like ${varName}
You should initialize your javascript file via your jsp file.
Example:
Create a seperate script section for initialization of your variables after loading the .js file in your jsp page:
<script src="js-path/file.js"></script>
<script>
init(${varFromModel1}, ...);
</script>
And define the init-method in your javascript file:
function init(param1, ...) {
// initialize variables of .js file here
}
Remember, for this to work, you need to ensure, that the model-attribute output has correct javascript syntax.

Passing data from my razor view to my js file

I'm searching for the best way to pass data from my razor view to my js file. For example, lets say we have a jquery dialog configured in the js file. For buttons text on this dialog, I would like to localize it (through resource files FR/NL/UK). The translations are available with #UserResource.ButtonDelete + #UserResource.ButtonCancel
Below are the different solutions I see:
Using the nice RazorJS nuget package to allows razor code inside my javascript file. It works pretty well. But the question is: is it a bad practice to compile js files in order to use razor syntax inside the scripts?
Declaring global variables in the js script file and assign value from the view like this:
In the view:
<script>
var labelButtonDelete = #UserResource.ButtonDelete;
</script>
In the js file:
alert('The text for my button is ' + labelButtonDelete);
What is the best way to pass data from razor to js file? Do you have another alternative?
Thanks anyway.
I've been using something like your second approach for some time without any issues. The only difference is that I'm using a singleton in my JS file to avoid polluting the global javascript namespace.
But if you will be doing more serious client side stuff, your Javascript code will follow a more object oriented structure, and from there you almost automatically get a single initialization/constructor path where you can pass your localized values.
That RazorJS looks nice, but I'm not sure if I'm comfortable mixing Javascript with Razor. Might do it for a small project, but I can see it becoming really messy if you have lots of Javascript files.
After all, I still consider the resources/localization code to be related to the view. The Javascript should only implement functionality in my opinion.

Categories

Resources