Home Best (or correct) way to use JavaScript with C#/Razor?
Reply: 1

Best (or correct) way to use JavaScript with C#/Razor?

Opa114
1#
Opa114 Published in 2018-02-12 17:15:35Z

What is the best and maybe correct way of mising JavaScript code with Razor? At the moment i put my JavaScript code in an external JavaScript file "external.js" but there i have the problem that i can not access the C# variables of my model directly (i can do it, but it makes the whole thing a little bit complicated). This only works with Razor-Syntax @Model.Variable when i embed my JavaScript Code inside the view in the -Section/Tags.

So i thought about this situation and don't find an answer. I read and thought it would be the best to put all JavaScript code in one file, so that the browser loads the whole stuff only one time and then read out of the cache (Performance). But could it be better to write the JavaScript code inside each View instead of putting into one huge file?

James Robert Pattison
2#
James Robert Pattison Reply to 2018-02-12 17:22:17Z

Putting your Javascript directly into your view isn't going to affect the load of your page in any significant manner (unless your Javascript really is a behemoth).

It will be transported (and subsequently cached) when the view is requested.

If you're wanting to use your razor variables directly in Javascript, then having it in the view is your most sensible option

That is, of course, the view is intended to be used as a partial - in which case you probably want to rethink the design

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308382 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO