简体   繁体   English

MVC4 Razor标签已换出JavaScript

[英]MVC4 Razor tags in swapped out JavaScript

I have a View using swapped out JavaScript 我有一个使用换出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: 我知道我可以直接在View中的JavaScript部分中调用Razor命令,如下所示:

<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: 现在,我需要调用一个自定义的HtmlHelperExtension方法,该方法从换出的.js文件中返回一个字符串值,但是当我将其写下来时:

var someVariable = '@(Html.someHtmlFunction())'

the part '@(Html.someHtmlFunction())' gets interpreted as string itself and my someVariable looks like "@(Html.someHtmlFunction())" instead of "someReturnValue". 部分“ @(Html.someHtmlFunction())”本身会解释为字符串,而我的someVariable看起来像“ @(Html.someHtmlFunction())”而不是“ 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? 是否可以从换出的JavaScript文件中调用Razor命令,还是必须在视图中包含JavaScript?

No, you can't do this in the .js file. 不,您不能在.js文件中执行此操作。 What I normally do in these scenarios is set the JavaScript variable on the page and reference it in the .js file. 在这些情况下,我通常要做的是在页面上设置JavaScript变量,然后在.js文件中引用它。 Ie use global variable: 即使用global变量:

in .cshtml: 在.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: 在Index.js中:

console.log(someVariable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM