I have several JS code in several partials Views.
I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.
But how do you deal with MVC code inside JS?
The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code @Url.Action("ResultForm", "File") and it will not be executed in JS file.
Any suggestion?
Javascript Code
<script type="text/javascript">
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: '@Url.Action("ResultForm", "File")',
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
</script>
I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:
in your view.cshtml
in you customScript.js
The idea is to separate out the Asp.Net MVC specific code from the js code.
The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.