Best practices for using JavaScript on partial views and views in ASP.MVC?

I began to delete part of the view in partial so that it could be reused on another view. However, I am stuck because there are some JavaScript functions on the original view that call some of the functions belonging to the partial. It seems wrong to call functions defined on a partial of the containing view (and vice versa). What is the best practice for this situation? Thanks.

+4
source share
3 answers

I created the application myself and came across this, although I have not implemented it yet, I plan to use jQuery plugins to do a lot of this. You cannot embed JS in partial view if you load partial through AJAX because it will not work.

JQuery is a very good infrastructure and easy to use plugins. You just need to start designing your JS so that it is more reusable (no links to hard code, etc.).

Alternatively, without jQuery, creating separate JS files and creating your own code using JS classes is also a good strategy.

NTN.

+1
source

I recommend that you use some ScriptManager and move all the js functions to external files, so you just need to register the required file for this partial in a partial view. See these links for more details:
Scriptmanager Asp.Net Mvc
http://mvcscriptmanager.codeplex.com/
http://www.telerik.com/help/aspnet-mvc/web-assets-working-with-javascript-web-assets.html

0
source

If the view may optionally contain a partial, it can check for the existence of the function before calling it:

if (typeof(foo) == 'function') { foo(); } 

Or, a view can determine the default version of a function, which can be overridden in part.

 // in view or master function foo() {} // then in the partial function foo() { /* does something */ } 
0
source

Source: https://habr.com/ru/post/1302375/


All Articles