JavaScript code in ASP.NET MVC Partial Views (ASCX) or not?

Is there a “best practice” for hosting Javascript code when you have a lot of partial views and the JS code that it defines?

It seems to me that I create a nightmare for maintenance, having many partial views, and then a bunch of independent Javascript files for them that need to be synchronized when a partial change of view occurs. It seems like for maintenance purposes it is better for me to put the partial representation JS code. But then I break the generally accepted practice that all JS codes should be at the bottom of the page and not mix, and I also get several links to the same JS file (since I would include a link in each ASCX for intellisense purposes).

Anyone have a better idea? Thanks!

+4
source share
2 answers

I do not know if there are many more established “best practices” than those that you have already stated in your question that you would like to join.

Recently, I have taken the Html Helper approach to common js / jQuery blocks that I need for certain complex “controls” that require a lot of ajax and UI js support. In my last case , I had two of these “controls”, and each needed 3 scripts.

I use this helper layout where I can use the syntax as follows:

<%-- // jQuery for Patron --%> <% =Html.MattyJq().DivListItemSingleSelector("selectPatronItem", "div#matchingPatrons", "patronsPrevSelectedID","PatronID") %> <% =Html.MattyJq().EmptyTextInputHelper("patronSearch", "patronsFilterSendEmpty") %> <% =Html.MattyJq().TextChangeDynamicUpdaterSelect("patronSearch","div#matchingPatrons", "/patrons/getpatronsitems",500,"patronsFilterSendEmpty","patron", "patronsPrevSelectedID","selectPatronItem") %> 

I have this "Template" folder in my MVC "/ Scripts" folder, where I put the script blocks and then mark all the "variables" with an escape sequence so that I can change / change in my variables that I went into helpers (above) as parameters.
This way I can reuse the templates and my looks are much easier / cleaner. You will notice the common parameters in the helpers there - that, for example, I have function names js or var , which are common to more than one script block. This is a kind of way to "link" isolated script blocks together.
Finally, I have a general section for helpers that allows me to “jump over” to the resulting js / jQuery with a parser if I choose - in my case I use .NET YUI Compressor to minimize js in Release versions - I'm sure you could add some logic here to make sure all the scripts were at the bottom of the page if you liked.

+1
source

Use one JS and unobtrusive javascript for the behavior layer on your html pages.

Throwing js all over the place is such a nightmare for maintenance, even with firebug.

Remember, always program as if the person supporting your code is a cruel psychopath.;)

0
source

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


All Articles