I have a View using swapped out JavaScript
@section JavaScript {
<script type="text/javascript" src="@Url.Content("/Scripts/Index.js")" />
}
I know I can call Razor commands in a JavaScript section directly within my View, like this:
<script type="text/javascript">
var someVariable = '@(Model.Name)'
</script>
Now, I need to call a custom HtmlHelperExtension Method returning a string value from my swapped out .js file, but when I write it down like this:
var someVariable = '@(Html.someHtmlFunction())'
the part '@(Html.someHtmlFunction())' gets interpreted as string itself and my someVariable looks like "@(Html.someHtmlFunction())" instead of "someReturnValue".
Is it possible to call a Razor command from within a swapped out JavaScript file or do I have to include the JavaScript in the View?
No, you can't do this in the .js file. What I normally do in these scenarios is set the JavaScript variable on the page and reference it in the .js file. Ie use global
variable:
in .cshtml:
var someVariable = '@(Html.someHtmlFunction())' // make sure this is before .js
@section JavaScript {
<script type="text/javascript" src="@Url.Content("/Scripts/Index.js")" />
}
in Index.js:
console.log(someVariable);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.