0

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?

2
  • odetocode.com/code/80.aspx Check that link Commented Jun 18, 2012 at 12:39
  • I write values like that into data- tags, or hidden values to consume in the script file. Commented Jun 18, 2012 at 12:41

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.