如何在 cshtml MVC3 Razor 页面上的 javascript 中嵌入 c# 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5195280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:06:45  来源:igfitidea点击:

How to embed c# code in javascript on cshtml MVC3 Razor page

javascriptasp.net-mvc-3razor

提问by stan4th

how would I do the equivalent of this embedded in JavaScript on an MVC2 aspx page:

我将如何在 MVC2 aspx 页面上执行嵌入在 JavaScript 中的等效项:

if (('<%= Model.SomeFunctionEnabled %>' == 'True')and also a whole function code block on a Razor view page (cshtml) in MVC3?

if (('<%= Model.SomeFunctionEnabled %>' == 'True')以及 MVC3 中 Razor 视图页面 (cshtml) 上的整个功能代码块?

Something like :

就像是 :

@{
    foreach(var d in Model.Employees)
    {
        ....
    }
}

Which works fine when embedded in the HTML part of the view page. Thanks

当嵌入到视图页面的 HTML 部分时,它工作正常。谢谢

回答by Darin Dimitrov

Why testing on the client side when you could do this on the server side and include the javascript to act accordingly if the test succeeds:

当您可以在服务器端执行此操作并包含 javascript 以在测试成功时进行相应操作时,为什么要在客户端进行测试:

<script type="text/javascript">
    @if (Model.SomeFunctionEnabled) {
        <text>
        // Put your javascript code here
        alert('the function is enabled');
        </text>
    }
</script>

回答by GvS

If you want to execute the logic in JavaScript:

如果要在 JavaScript 中执行逻辑:

if ('@Model.SomeFunctionEnabled' == 'True') {
}

But this results in a condition that always evaluates to the same outcome. So you are better with Darin's answer to do the whole testing on the server.

但这会导致始终评估为相同结果的条件。因此,您最好使用 Darin 的答案在服务器上进行整个测试。

If your test is however something dynamic like this, that cannot be executed on the server. You can get the contents of your C# variable by using a @sign.

但是,如果您的测试是这样的动态测试,则无法在服务器上执行。您可以使用@符号获取 C# 变量的内容。

@{
    var elementID = GetMyGeneratedElementID();
}

<div id="@elementID">...</div>
<script>
   function MyAmazingJavascriptElementHandler() {
       if ($("#@elementID").SomeTest()) {
          DoMyAmazingJavascript();
       }
   }
</script>