简体   繁体   中英

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

The problem is that one of the javascript functions uses C# code in order to get some data from model. 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?

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.

Think like 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.

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.

You could use a partial view to write the <script> tag and call that from both pages. You could also use an HTML helper if you think that's more suitable.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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