0

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?

1
  • You could have the static javascript accept parameters which the dynamic javascript in the view passes in when calling. Commented Feb 12, 2018 at 18:46

1 Answer 1

2

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

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

1 Comment

thanks for explanation, so for performance it did not make any significant manner, but what is the "default way" of doing this? I think many .net razor apps will use javascript or not? How do they work with that?

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.