Passing data from my razor view to my js file

我怕爱的太早我们不能终老 提交于 2020-01-03 05:00:13

问题


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.



来源:https://stackoverflow.com/questions/9616264/passing-data-from-my-razor-view-to-my-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!