Passing data from my razor view to my js file

2019-06-14 05:54发布

问题:

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:

  1. 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?

  2. 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.

回答1:

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.