I think this is a common scenario. I have a view where I use HtmlHelper to generate some HTML elements, I also have a helper extension that allows me to get the generated element identifier so that I can use it in JavaScript (e.g. jQuery):
$('#@Html.FieldIdFor(model => model.Name)').autocomplete({
Or, when I do Ajax, I am building a URL string from UrlHelper, again using the server side code to put some elements on the client side on the page:
$.get('@Url.Action("States", "Location")', { country: $(this).val() }, function (json) {
This part is simple. I know how to do this, and I know that I can put this code in partial and display a partial view where I want the code to be displayed. This is not what I want to ask.
The code contained in the page layout is not cached, this is one thing. Another thing is that sometimes I need the same bit of code for multiple views, and I would like to save it in one place for maintenance. One place may be partial, but I want this code to be cached, ideally it would fall into a .js file. However, we cannot use server-side code in .js files. Keywords are cachable and single file .
I also know that I can have a dispatcher that will serve JavaScript, for example:
<script src="@Url.Action("Script", "JS", { script = "location" }) type="text/javascript"></script>
This controller action may return JavaScript as a result of rendering the view.
Or maybe I should stop being paranoid and just use regular .js files and put the identifiers and URLs of the elements there, and if I ever update my models or views, I would go and update the .js files. I am wondering if this is due to a development problem with .NET. I would be interested to know how people do it in Rails or django.
What I'm really looking for is "best practice" strategies. What do you do most often? How do you solve this problem?