2

I'm working on an ASP .NET Core MVC application. On previous projects, I would put any page-specific JavaScript at the bottom of my View's .cshtml file. However, this project has more page-specific JavaScript and some have recommended using separate .js files, one per View. I've had trouble finding recommended patterns. One downside of separate .js files is that it's harder to inject data from the ViewModel or ViewBag which are available in .cshtml.

What are best practices for managing JavaScript in ASP .NET MVC apps?

We are considering the following, where each view would reference its respective .js file. But this still has the downside of not being able to access the ViewModel, ViewBag, and other helpers.

[wwwroot]
-  [js]
-    [src]
-      [mycontroller] // controller folders
-        index.js     // view js files
-        about.js
-      [othercontroller]
NSouth
  • 5,067
  • 7
  • 48
  • 83
  • In general, when I want to pass something to Javascript, I do it using a hidden input or a `data-*` attribute. That allows for a bit more separation of concerns; your javascript doesn't care who or how the field is populated, it's just grabbing a value from an element. As far as your folder hierarchy is concerned that's really up to personal preference, to me that layout looks fine – MichaelM Sep 28 '19 at 12:40
  • Possible duplicate of [Is it OK to put JavaScript in Partial Views](https://stackoverflow.com/questions/11098198/is-it-ok-to-put-javascript-in-partial-views) – Wahid Bitar Sep 29 '19 at 07:04

0 Answers0