简体   繁体   English

将C#代码插入(.js)javascript文件

[英]Insert C# code into (.js)javascript file

In the asp.net mvc 3 application I have two views which have the same set of javascript functions. 在asp.net mvc 3应用程序中,我有两个视图具有相同的javascript函数集。 Javascript is identical so I want to reorganize this code and extract all the javascript code into .js file in order to include it in both chtml files. Javascript是相同的,因此我想重新组织此代码并将所有JavaScript代码提取到.js文件中,以便将其包含在两个chtml文件中。

The problem is that one of the javascript functions uses C# code in order to get some data from model. 问题在于,其中一个javascript函数使用C#代码来从模型中获取一些数据。 How can I insert C# code into the javascript(.js) file or how can I extract all this code into a separate chtml file and include it in both of the previous? 如何将C#代码插入到javascript(.js)文件中,或者如何将所有这些代码提取到单独的chtml文件中,并将其包括在前两个文件中?

You can't natively, or at least you shouldn't. 您不能本机,或者至少不应该。 Both for maintenance and performance reason. 出于维护和性能原因。

You should instead redesign your javascript to have parameterized methods, and initialize the custom value from your views. 相反,您应该重新设计javascript以使其具有参数化方法,并从视图中初始化自定义值。

Think like jQuery. 像jQuery一样思考。 A lot of plugins are available, standardized, but they are initialized with specific value on pages that are consuming them. 有许多可用的,标准化的插件,但是在使用它们的页面上使用特定的值对其进行了初始化。

If your javascript contains different data then it's not identical. 如果您的JavaScript包含不同的数据,那么它是不相同的。

I would extract the identical functionality into a .js file, and either generate a chunk of javascript data in you page that the .js can use, or refactor to a service that returns JSON. 我会将相同的功能提取到.js文件中,或者在您的页面中生成.js可以使用的大量javascript数据,或者重构为返回JSON的服务。

You could use a partial view to write the <script> tag and call that from both pages. 您可以使用局部视图来编写<script>标记,然后在两个页面中进行调用。 You could also use an HTML helper if you think that's more suitable. 如果您认为更合适,也可以使用HTML帮助程序。

However, I wouldn't recommend either. 但是,我也不推荐。

One option is to find a way to put the values that change onto your page (possibly as html5 data- attributes), then use an external .js file for your JavaScript code, which is not manipulated by the C#, but instead gets the data from the HTML itself. 一种选择是找到一种方法,将更改的值放在页面上(可能是html5 data- attributes),然后将外部.js文件用于JavaScript代码,该文件不受C#的操纵,而是获取数据从HTML本身。

Another (not quite as beautiful) option would be to have each page set a series of JS variables in a <script> tag, then use them in your external .js file. 另一个(不太漂亮)的选择是让每个页面在<script>标记中设置一系列JS变量,然后在外部.js文件中使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM