How to organize the JavaScript Code in ASP.NET MVC

2020-03-01 06:41发布

问题:

We are to add some Ajax functions on a view page. Say, click a delete or insert button and an Action will be called to perform a CRUD job behind the scene and then refresh the items list after that operation.

In many existing examples, the javascript code is embeded in the view page within the <script> tag. Since there are usually many functions that one view may need. Say, when insert a record, there will be function to collect the form data, validate the data (this part can be very long), and call the action by $.ajax(). For this reason, we are thinking about place all those javascript into a separate .js file.

So, what is the professional practice in this? Should we place the .js files under the same folder with its Views? Or should be place all of them into the Script folder and reference from there?

Should we create seperate .js files for each individual view or combine all the .js files for different views into a large file?

Also, we love how we can group C# code using #region so as to collapse. Is there anything similar in JavaScript? It just grows lengthy too easily.

Thank you for any helpful advice.

回答1:

I wouldn't use the Scripts directory for this purpose, because all default JavaScript files (i.e. jQuery and others) are placed here. I generally use the Content directory for my own JavaScript (also CSS and images) files.

You can structure your files in seperate folders like your views (i.e. ~/Content/js/myviewfolder/somename.js).

If you want to structure your JavaScript code: you can seperate independant code into different files and you can let it process to one file. Or you can group it into an anonymous self executing code blocks, you can then collapse those blocks. Apart from that, I am out of ideas. (Personally, I would go for different files (there are ways if building different JavaScript files into one file.)