Structure for referencing HTML elements from Javascript in MVC3

We have an ASP.NET MVC3 project. We populate several parts of our site with ajax calls. Suppose we have a div in our cshtml where we want to put some search results.

 <div id="SearchResult" /> 

We created a list with constants for all the elements that we want to send in our Javascript files

 var selectors = { SearchResult: '#SearchResult', ... }; 

When we want to access the div , we use selectors.SearchResult in our Javascripts.

So far so good. But, based on the C # world, where we have strong bindings, compilation of time warnings, etc., we believe that the connection here is a bit on the side. If we want to reorganize our div identifiers, we must be very careful to find all the links and update them.

Is there any good practice for syncing javascript and HTML ids? Any patterns / scripts to extract all div identifiers into javascript file?

+4
source share
1 answer

Add script to view

 <script type="text/javascript"> window.viewConfig = { searchResult: '#SearchResult' }; </script> 

and your JS files read this window.viewConfig.searchResult .


You can also take this and save the identifier in a variable and use it.

 @{ var myId = "SearchResult"; } 

then use @myId so the div will be

 <div id="@myId"></div> 

and the script will be

 <script type="text/javascript"> window.viewConfig = { searchResult: '#@myid' }; </script> 
+2
source

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


All Articles