Passing data from my razor view to my js file - javascript

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.

Related

jinja2 variables in javascript

If I have written jinja2 variables in javascript, for example
var array = [{{count}}...
and it works, will it work even if I move the code to a separate js file? Is there anything else I need to know about this practice?
You can certainly create a Jinja2 template that contains Javascript with Jinja2 variables, render that into a JavaScript file, and serve it to your users. Jinja2 doesn't care what kind of file you are rendering.
An important consideration is that you are changing a static file to a dynamic file. A typical Javascript file is static but you are now making it dynamic which puts additional load on your servers.
A typical solution is to use static JavaScript but render JavaScript data into your HTML page that the JavaScript file can access.
I came across this looking for the same kind of solution, and it was pointed out to me somewhere else that the data attribute in HTML is a good solution here as well.

Best way to use C#-Ressources (ResX Files) in Typescript?

our current project is in ASP.Net MVC with Razor.
We use ResX Files for a few thousend translations.
In C# and Asp.net Razor this is pretty easy with HTML:
<div>#Ressources.Local.Test</div>
Now when I wrote JavaScript I normaly did this within the cshtml files with razor like this:
<script>alert('#Ressources.Local.Test');</script>
Which works but seems a bit ugly...
A few weeks ago we starded with Typescript, and, of course excluding (nearly) all javascript code to ts-files.
The only solution we found here, to get the ressources from C# to Typescript is through a "hack":
We made a ressources.cshtml file in which we just include javascript variables:
var ressourceTest = "#Ressource.Local.Test";
We load this ressource.cshtml at first in our _layout.cshtml.
Additional, we have a self need a selfmade declarion for this variable to jump from javascript to typescript in our projectDeclarions.d.ts:
var ressourceTest:string;
And now we can use the ressource in our typescript file test.ts:
alert(ressourceTest);
As you can see it is a working "hack" or "workaround" but it seems to likly kill us for a few thousend ressources... It's handmade, the maintain duration and work is high...
Any better ideas?
I have seen a few good ideas around this.
You could supply an JSON endpoint in your MVC application to give you chunks of translations. You would decide how granular you want to make it, but you would essentially JSON serialize a translation, or set of translations and send it back. This would avoid stuffing a big view with hundreds of the things.
Another alternative is to place translations in the view to make them available, but contextually. So if you had a button that you are using to trigger some AJAX call to the server and you need to say "Update Worked" or "Update Failed" you could put the attributes inline...
<button ... data-msg-success="Saved OK" data-msg-failed="A problem occurred" />
And you could populate these attributes with your resources.

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 transfer mvc view javascript code to separate js file

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.

What is the best way to organize JS code in webapps where the main "meat" is still server side?

When building webapps with MVC web framworks like Django, Kohana, Rails and the like, I put together the application without JS-driven components initially, and then add them afterwards as "improvements" to the UI.
This approach leads to non-intrusive JS, but I don't have a good "standard" way of how to go about organizing the JS work. Most of the JS I write in apps like these are 10-30 line JQuery snippets that hook into some very specific part of the UI.
So far I often end up inlining these things together with the part of the UI they manage. This makes me feel dirty, I'd like to keep the JS code as organized as the python / php / ruby code, I'd like for it to be testable and I'd like for it to be reusable.
What is the best way to go about organizing JS code in a setup like this, where we're not building a full-blown JS client app, and the main meat is still server side?
I am also very interested in what other people have to say about this. The approach I've taken is to use object literal notation to store the bulk of the function, and store these in one file included on all pages (the library)
uiHelper = {
inputDefault:function(defaulttext){
// function to swap default text into input elements
},
loadSubSection:function(url){
// loads new page using ajax instead of refreshing page
},
makeSortable:function(){
// apply jQuery UI sortable properties to list and remove non javascript controls
}
}
Then I include a .js file on any page that needs to use the library that ties the elements on that page to the function in the library. I've tried to make each function as reuseable as possible and sometimes the event binding function on the page calls several of my library functions.
$(document).ready(function(){
$('#mybutton').live('click',uiHelper.loadSubSection);
//more complicated helper
$('#myotherbutton').live('click',function(){
uiHelper.doThisThing;
uiHelper.andThisThing;
});
});
edit: using jsDoc http://jsdoc.sourceforge.net/ notation for commenting for these functions can produce documentation for the 'library' and helps keep your code easy to read (functions split by comments).
The following question is along similar lines to your own - you should check it out...
Commonly accepted best practices around code organization in JavaScript
When dealing with JS code, you should first analyze whether it will be used right away when the page loads. If it's not used right away (meaning the user must do something to invoke it) you should package this into a JS file and include it later so the load time is perceived faster for the user. This means that anything that the user will sees should go first and JS related to the functionality should be imported near the end of the file.
Download this tool to analyze your website: http://getfirebug.com/
If the JS code is small enough, it should just be inline with the HTML.
Hope that helps a bit.
For quick little user interface things like that I put everything into a single javascript file that I include on every page. Then in the javascript file I check what exists on the page and run code accordingly. I might have this in UIMagic.js for example. I have jQuery, so excuse those jQuery-isms if they aren't familiar to you.
function setupMenuHover() {
if ($("li.menu").length) { // The page has a menu
$("li.menu").hover(function() { ... }, function() { ... });
}
}
$(setupMenuHover);
function setupFacebookWizbang() {
if (typeof FB != "undefined") { // The page has Facebook's Javascript API
...
}
}
$(setupFacebookWizbang);
I've found this to be a sane enough approach.
My preferred method is to store inline javascript in it's own file (so that I can edit it easily with syntax highlighting etc.), and then include it on the page by loading the contents directly:
'<script type="text/javascript">'+open('~/js/page-inline.js').read()+'</script>'
This may not perform well though, unless your templating library can cache this sort of thing.
With Django you might be able to just include the js file:
<script type="text/javascript">
{% include "js/page-inline.js" %}
</script>
Not sure if that caches the output.
If you are still worried about being 'dirty', then you could check out the following projects, which try to bridge the server/client side language mismatch:
http://pyjs.org/ (Python generating JavaScript)
http://code.google.com/webtoolkit/ (Java generating JavaScript)
http://nodejs.org/ (JavaScript all the way!)

Categories

Resources